2012-01-31 52 views
3

我是Ruby的新手,我該如何做這樣的事情?在C#中,我會寫Ruby的等價LINQ ToList()

my_block().ToList() 

它會工作。

我想象這個功能

def my_block 
    yield 1 
    yield 2 
    yield 3 
end 

my_block.to_enum().map {|a| a} 

這給了我這個錯誤:

test.rb:2:in `my_block': no block given (yield) (LocalJumpError) 
    from test.rb:7:in `<main>' 

,這是什麼行爲,正確的咒語?

回答

5

爲您的代碼正確的語法是:

to_enum(:my_block).to_a # => [1,2,3] 

Object#to_enum願與方法名作爲參數符號:

to_enum(method = :each, *args)
enum_for(method = :each, *args)

Creates a new Enumerator which will enumerate by on calling method on obj.

等效爲C#ToList()Enumerable#to_a

to_a → array
entries → array

Returns an array containing the items in enum.

+0

很酷,我不知道。 – 2012-01-31 16:50:29

1

你可以改變你的功能,所以它返回一個枚舉。下面是如何會看一個例子:

def foo 
    Enumerator.new do |y| 
    y << 1 
    y << 2 
    y << 3 
    end 
end 

p foo  # => <Enumerator: #<Enumerator::Generator:0x1df7f00>:each> 
p foo.to_a # => [1, 2, 3] 
p foo.map { |x| x + 1 } # => [2, 3, 4] 

然後你可以使用任何的可枚舉模塊中的方法就可以了:

http://ruby-doc.org/core-1.9.3/Enumerable.html

標準庫很多紅寶石功能如果它們在被調用時沒有通過一個塊,它將返回一個枚舉值,但是如果它們通過了一個塊,它們將產生值給塊。你也可以這樣做。

+0

小修正,ruby 1.9中的這些函數將返回[Enumerator](http://www.ruby-doc.org/core-1.9.3/Enumerator.html),而不是Enumerable,因爲您可能錯誤輸入了答案。枚舉器包含Enumerable模塊。 – 2012-01-31 17:02:03

+0

是的。該函數返回的對象是一個Enumerator,它也是一個Enumerable。 'foo.is_a?(Enumerable)'返回true。對於多重繼承,我認爲可以說一個對象是多重事物。我並不特別在乎函數是否返回一個Enumerator,我只關心它是否返回一個Enumerable,因爲它決定了我是否可以像'collect'和'select'一樣使用所有有用的方法。 – 2012-01-31 17:12:10

+0

謝謝大衛,我不知道這種方法。我可以看到它有助於構建更多行爲良好的庫 Alex的方法更加簡潔,滿足我的需求,並且不需要我更改調用函數,只需調用者即可。這就是說,你的答案仍然是正確的。但我想我只能有一個答案... – Doug 2012-01-31 17:48:31