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

前端 未结 9 2080
清酒与你
清酒与你 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-31 07:14

    You can use instance_of?

    e.g

    @some_var.instance_of?(Hash)
    
    0 讨论(0)
  • 2021-01-31 07:15
    Hash === @some_var #=> return Boolean
    

    this can also be used with case statement

    case @some_var
    when Hash
       ...
    when Array
       ...
    end
    
    0 讨论(0)
  • 2021-01-31 07:17

    You can just do:

    @some_var.class == Hash
    

    or also something like:

    @some_var.is_a?(Hash)
    

    It's worth noting that the "is_a?" method is true if the class is anywhere in the objects ancestry tree. for instance:

    @some_var.is_a?(Object)  # => true
    

    the above is true if @some_var is an instance of a hash or other class that stems from Object. So, if you want a strict match on the class type, using the == or instance_of? method is probably what you're looking for.

    0 讨论(0)
  • 2021-01-31 07:17

    I use this:

    @var.respond_to?(:keys)
    

    It works for Hash and ActiveSupport::HashWithIndifferentAccess.

    0 讨论(0)
提交回复
热议问题