什么是Ruby的一个简单/优雅的方式来判断一个特定变量是一个哈希或数组? [英] What is a simple / elegant way in Ruby to tell if a particular variable is a Hash or an Array?

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

问题描述

要检查什么 @some_var 是,我做了

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

我肯定有一个更优雅的方式来检查 @some_var 哈希阵列

推荐答案

您可以这样做:

@some_var.class == Hash

或也类似:

@some_var.is_a?(Hash)

值得注意的是,is_a?如果类中的对象祖先树的任何位置的方法是正确的。例如:

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是,从对象茎散列或其它类的一个实例的上述是真实的。所以,如果你想在类的类型严格的匹配,使用==或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天全站免登陆