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

前端 未结 9 2091
清酒与你
清酒与你 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条回答
  •  梦毁少年i
    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
    

提交回复
热议问题