Reputation: 332
Let's say I have a method that has the following...
def is_number?(a,b,c,d)
# ... check if the argument is a number
end
Is it possible to iterate through each argument passed to is_number?
and do what is within the method?
For example...
is_number?(1,3,"hello",5)
Would go through each argument and if the argument each argument is a number it would return true, but in this case, it would return false due to "hello"
.
I already know how to check if an input is a number, I just want to be able to check numerous arguments all in one method.
Upvotes: 4
Views: 1380
Reputation: 81691
Code golfing sawa's answer: same length, but avoids |
def is_number?(*args)
(args - args.grep(Fixnum)).empty?
end
is_number?(1,2,3) # => true
is_number?(5,2,"foo") # => false
It'd be nice if there was a grep -v , but currently there isn't one.
Upvotes: 4
Reputation: 168269
def is_number? *args; args.all?{|a| a.kind_of?(Fixnum)} end
Replace Fixnum
if you want a different class to match.
Upvotes: 3