I'm really new to Ruby. I have the following scenario where - I need to check if a keyword is an array or not in ruby?
Something like this -
if(value == array) {
do something
}
else
do something
How can I do so using the if condition in ruby?
Any teachings would be really appreciated.
CodePudding user response:
Update:
You can get the class of an Object with .class
, and you can get a boolean response by using .class.is_a?(Class)
:
ary = []
ary.class => Array
hsh = {}
hsh.class => Hash
float = 10.456
float.class => Float
# and get boolean responses like this:
hsh.class.is_a?(Hash) => true
hsh.class.is_a?(Array) => false
So you can handle each Class
independently. If there are lots of potential classes, use a case
statement:
case value.class
when Array
# do something to the array
when Hash
# do something to the hash
when Float
# do something to the float
when Integer
# do something to the integer
...
end
Old:
You can use .include?()
array = ['a', 'b', 'c']
array.include?('c') => true
array.include?('d') => false
So for your example:
if array.include?(value)
# do something
else
# do something else
end
CodePudding user response:
if value.is_a?(Array)
# do something
else
# do something else
end
OR
if value.kind_of?(Array)
# do something
else
# do something else
end
#kind_of?
and #is_a?
have identical behavior.
Ruby: kind_of? vs. instance_of? vs. is_a?