未定义的方法'反向'为500

时间:2013-10-14 04:56:13

标签: ruby

我刚刚学习红宝石,这似乎是我在这里做的一个容易的错误吗?

def palindromic(str)
    str.to_s
    if str.reverse == str
        puts "it is a palindromic number!"
    end
end

palindromic(500)

相反,我收到了错误

Project4.rb:5:in `palindromic': undefined method `reverse' for 500:Fixnum (NoMet
hodError)
        from Project4.rb:10:in `<main>'

1 个答案:

答案 0 :(得分:5)

您需要将行str.to_s更改为str=str.to_s。下面将举例说明原因:

num = 12
num.to_s # => "12"
num # => 12
num=num.to_s
num # => "12"

基本上String#to_s将接收者实例更改为String的实例。但如果接收者已经是String实例,那么接收者本身将被返回。

ar = [1,2]
ar.object_id # => 77603090
ar.to_s.object_id # => 77602480
str = 'Hello'
str.object_id # => 77601890
str.to_s.object_id # => 77601890