Is this a correct use of symbols in Ruby?

114 Views Asked by At

I am working on a code challenge using symbols on line 4. What is the code on line 4 doing? Is line 4 not using symbols correctly???

 1  class NameThingy
 2
 3    def format_name(name) 
 4        return "#{name[:last]}, #{name[:first]}"
 5    end
 6
 7    def display_name(name)
 8       puts format_name(name)
 9    end
10
11  end


my_name = NameThingy.new#("Jessica Flores")
my_name.format_name("Jessica Flores")
my_name.display_name("Jessica Flores")

When I run this, I get this error message:

test.rb:6:in `[]': can't convert Symbol into Integer (TypeError)
from test.rb:6:in `format_name'
from test.rb:17:in `<main>'
1

There are 1 best solutions below

3
On

This is because name is an String in your case any how, not a Hash. Look one example for the same :

name = "good"
name[:a]
# `[]': no implicit conversion of Symbol into Integer (TypeError)

When you did method call like my_name.format_name("Jessica Flores"), name, is then holding the reference to the String instance "Jessica Flores". Now String#[] expects only as its arguments either numeric number or range or regexp or string. But not symbol as per the documentation.

I would write your code as below :

class NameThingy

  def format_name(name)
    return name.split(" ").join(",")
  end

  def display_name(name)
    puts format_name(name)
  end

end

my_name = NameThingy.new
my_name.format_name("Jessica Flores")
my_name.display_name("Jessica Flores")
# >> Jessica,Flores