这是在Ruby中正确使用符号吗? [英] Is this a correct use of symbols in Ruby?
问题描述
我正在使用第4行上的符号来应对代码挑战. 第4行的代码在做什么? 第4行没有正确使用符号吗?
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")
运行此命令时,出现以下错误消息:
test.rb:6:in `[]': can't convert Symbol into Integer (TypeError)
from test.rb:6:in `format_name'
from test.rb:17:in `<main>'
推荐答案
这是因为在您的情况下,name
是String
,而不是Hash
.看一个相同的例子:
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)
当您进行了my_name.format_name("Jessica Flores")
, 名称 之类的方法调用时,该引用将保留对String
实例"Jessica Flores"
的引用.现在 String#[]
预期仅其参数为数字或 range 或 regexp 或 string .但不是符号.
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
这篇关于这是在Ruby中正确使用符号吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!