Checking each argument in a method?

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 over each argument passed in is_number?and execute what is inside the method?

For instance...

is_number?(1,3,"hello",5)

It will go through each argument, and if the argument of each argument is a number, it will return true, but in this case it will return false due to "hello".

I already know how to check if the input is a number, I just want to be able to check multiple arguments in one method.

+3
source share
2 answers
def is_number? *args; args.all?{|a| a.kind_of?(Fixnum)} end

Replace Fixnumif you want another class to match.

+3
source

Code golfing sawa replies: 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 would be nice if there was grep -v, but there is currently no one .

+3
source

All Articles