【问题标题】:ruby code with the NoMethodError带有 NoMethodError 的 ruby​​ 代码
【发布时间】:2016-08-27 16:10:32
【问题描述】:

运行以下 Ruby 代码时:

#!/usr/bin/env ruby
ar=[]

class String
   def to_int
     self == self.to_i
   end
end

ARGV.each do |a|
  ar.push("#{a}")
end

ar.map(&:to_int).sort

ar.each do |x|
  print x + " "
end

puts ""

我收到以下错误:

example.rb:14:in `sort': undefined method `' for false:FalseClass (NoMethodError)

该程序需要使用带有数字列表的命令行参数运行。任何帮助将不胜感激。

【问题讨论】:

  • 那么这个程序的预期输入输出是什么?
  • 加速输出为:ruby example.rb 5 4 1 3 2 输出:1 2 3 4 5

标签: ruby nomethoderror


【解决方案1】:
ARGV.sort.each { |x| print x + " " }
puts

【讨论】:

    【解决方案2】:
    class String
       def to_int
         self == self.to_i
       end
    end
    

    这个to_int 方法将返回真或假。所以当你运行这行代码时:ar.map(&:to_int).sortmap 方法会将整个数组映射为真或假。

    你的数组看起来像[false,false,true,false],当你运行sort 函数时它会失败。

    我不确定to_int函数的用途是什么,你只需要用简单的to_i函数映射,然后排序。

    ar.map!(&:to_i).sort
    

    确保使用map!,以便修改原始数组。

    如果您确实将数组映射为整数,则必须将打印行修改为

    ar.each do |x| 
      print x.to_s + " "
    end
    

    否则会报错:

    字符串不能被强制转换为 Fixnum

    【讨论】:

      【解决方案3】:

      当我使用 Ruby 2.3.0 运行它时,我没有收到该错误。 我尝试了 Ruby 2.0.0p648(OS X 附带)、2.1.5 和 2.2.4,它们也没有引发该错误。

      我有点不清楚你想在这里完成什么。 你做的事情没有任何意义,但我假设你正在尝试学习 Ruby,而你只是在尝试不同的事情。

      #!/usr/bin/env ruby
      ar=[]
      
      # This is "monkey patching" String, and is a bad practice.
      class String
        # A method named "to_int" implies a conversion to integer. But the "to_i" method already does
        # that, and this method doesn't convert to an integer, it converts to a boolean.
         def to_int
           # Comparing the string to itself as an integer. Why would it ever be true?
           self == self.to_i
         end
      end
      
      # I'm assuming that this is intended to convert the argument list to a list of strings.
      # But ARGV should already a list of strings.
      # And this would be better done as `ar = ARGV.map(&:to_s)`
      ARGV.each do |a|
        ar.push("#{a}");
      end
      
      # This creates an array of values returned by `to_int`, then sorts the array.
      # Since `String#to_int` (defined above) returns booleans, it's an array of "false" values, so
      # sorting does nothing. But then the value of the `sort` is ignored, since it's not assigned to
      # a variable. If you want to modify the order of an existing array, use `sort!`.
      # But if you're trying to sort the array `ar` by the numeric values, `ar.sort_by(&:to_i)` would
      # do that.
      ar.map(&:to_int).sort
      
      ar.each do |x| print x + " "; end
      
      puts ""
      

      您似乎正在尝试按数字顺序打印参数。 这可以通过

      来完成
      puts ARGV.sort_by(&:to_i).join(" ")
      

      【讨论】:

      • 非常感谢您对 Robin Daugherty 的帮助。这解决了我的问题。非常感谢。 :)
      猜你喜欢
      • 1970-01-01
      • 2017-04-07
      • 2016-07-15
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多