0

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.

  • Try `if value.class == Array...`. – Cary Swoveland Nov 11 '22 at 21:57
  • Yoru question is very unclear. What does this have to do with Ruby on Rails? What doe you mean by "I need to check if a keyword is an array or not in ruby?" A keyword is a keyword, it can never be an array. The only keywords in your code snippet are `if`, `do`, and `else`, and obviously none of them are arrays – they are keywords. – Jörg W Mittag Nov 12 '22 at 07:00

2 Answers2

1

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
Chiperific
  • 4,428
  • 3
  • 21
  • 41
1
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?

BenFenner
  • 982
  • 1
  • 6
  • 12