Ruby 把论点变成接受者

Ruby 把论点变成接受者,ruby,Ruby,我创建了以下扩展 class String def is_a_number? s # check if string is either an INT or a FLOAT (12, 12.2, 12.23 would return true) s.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true end end 如何使其作为链接方法工作 is_a_number?("10") # returns true "1

我创建了以下扩展

class String
  def is_a_number? s  # check if string is either an INT or a FLOAT (12, 12.2, 12.23 would return true)
    s.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
  end
end
如何使其作为链接方法工作

is_a_number?("10") # returns true
"10".is_a_number? # returns an error (missing arguments)
更新

感谢sawa、mikej和Ramon的回答。正如建议的那样,我将类更改为Object并删除了参数:

现在它工作得非常好:

23.23.is_a_number? # > true
谢谢大家…

当你们写
“10”的时候,你已经有了想要检查的对象
“10”
,它是
的接收者,所以你的方法不需要任何参数

因为
match
String
上的一个实例方法,所以不需要为它指定接收者。它将只在调用了
的对象上运行。因为您知道已经有了
字符串
对象,所以也不需要
to_s

就这样写吧:

class String
  # check if string is either an INT or a FLOAT (12, 12.2, 12.23 would return true)
  def is_a_number? 
    match(/\A[+-]?\d+?(\.\d+)?\Z/) != nil
  end
end
如果您不知道要测试的对象是否是字符串,建议您将扩展名放在
对象上,而不是放在
字符串上


此外,您所描述的并不是方法链接的真正含义;它只是在对象上调用一个方法。方法链接是在其中设置方法的返回类型,以便可以按顺序调用多个方法,例如在Rails中,类似

User.where(:name => 'Mike').limit(3) # find the first 3 Mikes
是方法链接的一个示例。

当您编写
时,“10”是一个数字吗?
,您已经有了要检查的对象
“10”
,它是
是一个数字的接收者,因此您的方法不需要任何参数

因为
match
String
上的一个实例方法,所以不需要为它指定接收者。它将只在调用了
的对象上运行。因为您知道已经有了
字符串
对象,所以也不需要
to_s

就这样写吧:

class String
  # check if string is either an INT or a FLOAT (12, 12.2, 12.23 would return true)
  def is_a_number? 
    match(/\A[+-]?\d+?(\.\d+)?\Z/) != nil
  end
end
如果您不知道要测试的对象是否是字符串,建议您将扩展名放在
对象上,而不是放在
字符串上


此外,您所描述的并不是方法链接的真正含义;它只是在对象上调用一个方法。方法链接是在其中设置方法的返回类型,以便可以按顺序调用多个方法,例如在Rails中,类似

User.where(:name => 'Mike').limit(3) # find the first 3 Mikes

是方法链接的一个示例。

似乎您希望修补
对象,而不是
字符串(因为您正在调用
):


您还可以考虑将其替换为
以验证模型上的数值性:true

似乎您希望修补
对象而不是
字符串
(因为您正在调用
):

您还可以考虑将其替换为
验证模型上的数值性:true