运行以下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:在`sort&#39 ;: undefined method`< =>' for false:FalseClass(NoMethodError)
此程序需要使用带有数字列表的命令行参数运行。任何帮助将不胜感激。
答案 0 :(得分:0)
ARGV.sort.each { |x| print x + " " }
puts
答案 1 :(得分:0)
class String
def to_int
self == self.to_i
end
end
此to_int
方法将返回true或false。因此,当您运行此行:ar.map(&:to_int).sort
时,map
方法会将整个数组映射为true或false。
您的数组看起来像[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
答案 2 :(得分:0)
当我使用Ruby 2.3.0运行时,我没有收到该错误。 我尝试过Ruby 2.0.0p648(OS X附带),2.1.5和2.2.4,它们也没有引发错误。
我有点不清楚你要在这里完成什么。 你做的事情没有任何意义,但我会假设你正在尝试学习Ruby而你只是尝试不同的事情。
if(line.toLowerCase().contains("skype")) {
// do what you want if skype is running
} else {
// do what you want if skype is not running
}
您似乎正在尝试按照数字顺序打印参数。 这可以通过
完成#!/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 ""