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.

2
  • Try if value.class == Array.... Commented Nov 11, 2022 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. Commented Nov 12, 2022 at 7:00

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

5 Comments

I think you got it wrong. Here "value" maybe an array name or a float name. So I need to figure out if that is array/float using if loop. Here "value" is not the typical values we have in array.
Are you saying "value" could be a class? like Array, Float, Integer, String, etc.?
Yes, value may be the name of array or name of a float. Suppose if value is an array it may have value = {0.1,0.2,0.3} .If it is a float just simply value = 0.1 or so.
case value.class -- case value is enough
@mechnicov, OP is new to Ruby and I thought that abstraction might be more confusing.
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.