【问题标题】:Checking variable type in Ruby在 Ruby 中检查变量类型
【发布时间】:2015-12-30 08:42:04
【问题描述】:

我在检查 ruby​​ 中的变量类型时遇到问题。这是我想在 ruby​​ 中复制的 python 示例代码。我想检查input 类型:是字符串、整数还是列表,然后进行特定的打印操作。

def printing (input):
    if type(input) == type(""):
        pass
    elif type(input) == type(1):
        pass
    elif type(input) == type([]):
        pass
    elif type(input) == type({}):
        pass
    elif type(input) == type(()):
        pass

我找不到可以在 ruby​​ 中执行此操作的方法。下面的代码是我想要的样子。我假设我必须在案例阶段检查类型。

def printing (element)
    case element
    when element.type("")
        puts element
    when element.type(2)
        puts element
    when element.type({})
        element.each_pair { |name, val|  print "#{name} : #{value}"}
    when element.type([])
        element.each {|x| print x}
    end
end

【问题讨论】:

标签: python ruby


【解决方案1】:

我认为您正在寻找Object#class。这里:

element = {}
element.class
# => Hash
a = []
a.class
# => Array

这将使您的开关盒如下:

case element
when String
 # do something
when Fixnum
 # do something
when Hash
 # do something
when Array
 # do something
end

注意: 正如下面 cmets 中的@ndn 所提到的,case 语句中不应包含 .class(我最初在我的回答中使用过)You can find the explanation here.

【讨论】:

  • @ndn 请取消删除您的答案。和这个不一样。
  • 感谢您的帮助。我整天都在寻找解决方案并阅读文档。
  • 到目前为止,这个答案是正确的,但这是由于在 ndn 的原始答案之后六分钟进行的编辑,这是正确的。
【解决方案2】:

这不是“正确答案”,我只是想指出你不应该在 python 中使用 type 你应该使用 isinstance 来代替

isinstance(input, list) # test for list
isinstance(inpit, [float, int]) # test for number

如果你使用的是 python 3,你可以检查抽象基类

import collections
isinstance(input, collections.abs.Sequence) # sequence = tuple, list and a lot of other stuff that behaves that way

【讨论】:

  • 感谢您的提醒。我会记下来的。
猜你喜欢
  • 2021-01-13
  • 1970-01-01
  • 2012-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-07
  • 2011-04-12
相关资源
最近更新 更多