Arrays 未定义的方法';流行音乐';用红宝石?
我有这个密码Arrays 未定义的方法';流行音乐';用红宝石?,arrays,ruby,string,methods,Arrays,Ruby,String,Methods,我有这个密码 def longest_word(sentence) long_word = "" sentence.split(" ").sort_by {|x| x.length} long_word = sentence.pop return long_word end p longest_word("hello dogs are fast") 当我试着运行它时,我得到了一个错误,方法“pop”是未定义的。这和文件有关吗?我想我已经准备好了。你在句子上调用弹出,这是一个
def longest_word(sentence)
long_word = ""
sentence.split(" ").sort_by {|x| x.length}
long_word = sentence.pop
return long_word
end
p longest_word("hello dogs are fast")
当我试着运行它时,我得到了一个错误,方法“pop”是未定义的。这和文件有关吗?我想我已经准备好了。你在
句子上调用弹出,这是一个字符串
你可能想要这个:
long_word = sentence.split(" ").sort_by {|x| x.length}.pop
split
和sort\u by
不以任何方式更改变量,它们返回一个新值。因此,如果您不将其分配给某个对象,语句
仍然是一个字符串
,“你好狗很快”
,而字符串没有#pop
sentence = sentence.split(" ").sort_by {|x| x.length}
您正在对字符串语句
调用数组方法pop
,而不是从split
字符串数组中接收
顺便说一下,您的代码可以简化:
def longest_word(sentence)
sentence.split(' ').sort_by(&:length).pop
end
p longest_word("hello dogs are fast")
#=> "hello"
您还可以使用:
sentence.split(" ").max_by(&:length)