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>'
This is because
name
is anString
in your case any how, not aHash
. Look one example for the same :When you did method call like
my_name.format_name("Jessica Flores")
, name, is then holding the reference to theString
instance"Jessica Flores"
. NowString#[]
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 :