What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

前端 未结 9 2090
清酒与你
清酒与你 2021-01-31 07:02

To check what @some_var is, I am doing a

if @some_var.class.to_s == \'Hash\' 

I am sure there is a more elegant way to check if

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 07:08

    In practice, you will often want to act differently depending on whether a variable is an Array or a Hash, not just mere tell. In this situation, an elegant idiom is the following:

    case item
      when Array
       #do something
      when Hash
       #do something else
    end
    

    Note that you don't call the .class method on item.

提交回复
热议问题