在Ruby中,有什么优雅的方法可以判断变量是哈希还是数组? [英] What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

查看:633
本文介绍了在Ruby中,有什么优雅的方法可以判断变量是哈希还是数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要检查@some_var是什么,我正在做

To check what @some_var is, I am doing a

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

我敢肯定,有一种更优雅的方法可以检查@some_varHash还是Array.

I am sure there is a more elegant way to check if @some_var is a Hash or an Array.

推荐答案

您可以这样做:

@some_var.class == Hash

或类似的东西:

@some_var.is_a?(Hash)

值得注意的是"is_a?"如果该类在对象祖先树中的任何位置,则该方法为true.例如:

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

如果@some_var是源自Object的哈希或其他类的实例,则上述情况成立.因此,如果要对类类型进行严格匹配,请使用==或instance_of?方法可能是您要寻找的.

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.

这篇关于在Ruby中,有什么优雅的方法可以判断变量是哈希还是数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆