I created the following extension
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
How can I make it work as a chained method?
is_a_number?("10") # returns true
"10".is_a_number? # returns an error (missing arguments)
Update
Thanks sawa, mikej and Ramon for their answers. As suggested, I changed the class to Object and got rid of the argument (s):
class Object
def is_a_number? # check if string is either an INT or a FLOAT (12, 12.2, 12.23 would return true)
to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) != nil
end
end
It now works perfectly fine:
23.23.is_a_number? # > true
Thanks guys…
When you write
"10".is_a_number?, you already have the object"10"you want to check for, which is the receiver ofis_a_number?, so your method doesn’t need to take any parameters.Because
matchis an instance method onString, you don’t need to specify a receiver for it. It will just operate on the same object on whichis_a_number?was called. Because you know you already have aStringobject, theto_sisn’t needed either.Just write it as:
Ramon’s suggestion that you may want to put your extension on
Objectrather than onStringis a good point if you don’t know if the object you’re testing is going to be a string.Also, what you’re describing isn’t really what is meant by method chaining; it’s just calling a method on an object. Method chaining is where the return types of methods are set up so that several methods can be called in sequence e.g in Rails, something like
is an example of method chaining.