2017-06-20 9 views
0

私はmyFilterというメソッドを持っています。これは配列を取り込み、要件を満たさない要素をフィルタリングします。ルビメソッドを変更してコードブロックを取り込む方法はありますか?

たとえば、彼らは私がこれをプリフォームだろうか5.

にすべて以上であるため、

arr = [4,5,8,9,1,3,6] 

answer = myfilter(arr) {|i| i>=5} 

この実行には、要素の5,8,9,6を持つ配列を返すでしょうか?アルゴリズムは簡単ですが、私はその状態をどのようにとるのか分かりません。

ありがとうございます。

+2

あなたはこのような方法があると書いてありましたが、結局はそのような方法がないようです。 – sawa

+0

メソッドmyFilterにコードを表示できますか? – garyh

+0

あなたは 'myfilter(arr){...}'が 'arr.select {...}'と同じであることに気づいていますか? – Stefan

答えて

0

あなたはその後、

my_filter([1, 2, 3]) { |e| e > 2 } 
=> [3] 

を呼び出す

def my_filter(arr, &block) 
    arr.select(&block) 
end 

を行うことができますが、代わりに、あなただけの直接ブロック:)私はあなたがしたくない当たり前の

+0

これは大変ありがとうございます – EaEaEa

3

selectを呼び出すことができますselectメソッドなどを使用しますが、ブロックの仕組みを理解したいと考えています。

def my_filter(arr) 
    if block_given? 
    result = [] 
    arr.each { |element| result.push(element) if yield element } # here you use the block passed to this method and execute it with the current element using yield 
    result 
    else 
    arr 
    end 
end 
+2

このメソッドをブロックなしで呼び出せるようにするには、 'return enum_for(:myfilter、* args)?block_given? ' – mudasobwa

2

慣用的な方法は、次のようになります。Enumerator::Lazy#enum_for

def my_filter(arr) 
    return enum_for(:my_filter, arr) unless block_given? 

    arr.each_with_object([]) do |e, acc| 
    acc << e if yield e 
    end 
end 

詳細情報。

関連する問題