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

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

    First of all, the best answer for the literal question is

    Hash === @some_var
    

    But the question really should have been answered by showing how to do duck-typing here. That depends a bit on what kind of duck you need.

    @some_var.respond_to?(:each_pair)
    

    or

    @some_var.respond_to?(:has_key?)
    

    or even

    @some_var.respond_to?(:to_hash)
    

    may be right depending on the application.

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

    Usually in ruby when you are looking for "type" you are actually wanting the "duck-type" or "does is quack like a duck?". You would see if it responds to a certain method:

    @some_var.respond_to?(:each)
    

    You can iterate over @some_var because it responds to :each

    If you really want to know the type and if it is Hash or Array then you can do:

    ["Hash", "Array"].include?(@some_var.class)  #=> check both through instance class
    @some_var.kind_of?(Hash)    #=> to check each at once
    @some_var.is_a?(Array)   #=> same as kind_of
    
    0 讨论(0)
  • 2021-01-31 07:32
    irb(main):005:0> {}.class
    => Hash
    irb(main):006:0> [].class
    => Array
    
    0 讨论(0)
提交回复
热议问题