Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking each argument in a method?

Tags:

ruby

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.

like image 989
user1015523 Avatar asked Oct 27 '25 02:10

user1015523


2 Answers

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.

like image 134
Andrew Grimm Avatar answered Oct 28 '25 17:10

Andrew Grimm


def is_number? *args; args.all?{|a| a.kind_of?(Fixnum)} end

Replace Fixnum if you want a different class to match.

like image 33
sawa Avatar answered Oct 28 '25 16:10

sawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!