Is this a correct use of symbols in Ruby?

旧时模样 提交于 2019-12-11 04:19:07

问题


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:


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


来源:https://stackoverflow.com/questions/20723533/is-this-a-correct-use-of-symbols-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!