English 中文(简体)
如何检查一个对象在 Ruby 是否可使用?
原标题:How to check if an object is iterable in Ruby?
  • 时间:2012-05-25 14:56:37
  •  标签:
  • ruby

我该如何检查一个物体在Ruby的可通行性?

也就是说,我想要一种方法 干净检查,如果一个物体是可循环的, 就像这样:

def is_iterable(my_object)
  ..
end

我真的不知道该从这个方法中 如何开始 明确命名类别。

Edit: For my purposes, let s say iterable is something you can do .each to.

最佳回答

为了我的目的,让我们说,可以使用的东西 你可以做 . each to.

您可以只询问此对象是否有此方法

def iterable?(object)
  object.respond_to?(:each)
end
问题回答

这样做有若干种方法,这取决于你的大目标,也取决于你对结果需要做些什么。

  1. 如果您只想使用鸭键键来查看对象是否响应“强'each

    my_object.respond_to? :each
    
  2. 如果您想要知道对象是否混合在可计数类中,您可以检查该类是否包含。

    my_object.class.include? Enumerable
    
  3. 如果您想要一份所有祖先和混凝土的清单, 您想要 < a href=" http:// ruby- doc. org/core-1.9.3/ Module.html#method- i- 祖先" rel= “ noreferrer”\\ ancestors < / a > 方法。 例如, 您可以引用 :

    my_object = []
    my_object.class.ancestors
    => [Array, Enumerable, Object, PP::ObjectMixin, Kernel, BasicObject]
    
    my_object.class.ancestors.include? Enumerable
    => true
    

因为 Range 响应 each , 即使它无法循环, 您也需要具体检查范围元素响应 succ

def iterable?(object)
  return object.begin.respond_to? :succ if object.kind_of? Range
  object.respond_to? :each
end

一般情况下,您可以检查 ach 方法是否被定义,或者 Enumberable 模块是否包含在对象类中 :

my_object.class.include? Enumerable

Minitest -style 测试插件 ActiveRecord 构成对象:

def test_iterates_over_invoice_items
  invoice = Invoice.new(items: [InvoiceItem.new(description:  test )])

  iteration_count = 0
  invoice.each do |invoice_item|
    assert_equal  test , invoice_item.description
    iteration_count += 1
  end

  assert_equal 1, iteration_count
end




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签