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

前端 未结 9 2301
清酒与你
清酒与你 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:10

    If you want to test if an object is strictly or extends a Hash, use:

    value = {}
    value.is_a?(Hash) || value.is_a?(Array) #=> true
    

    But to make value of Ruby's duck typing, you could do something like:

    value = {}
    value.respond_to?(:[]) #=> true
    

    It is useful when you only want to access some value using the value[:key] syntax.

    Please note that Array.new["key"] will raise a TypeError.

提交回复
热议问题