EaEaEa
EaEaEa

Reputation: 21

How can I modify my ruby method so it takes in a block of code as well?

I have a method called myFilter that takes in an array, and filters out the elements that don't meet the requirement.

For example.

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

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

this run would return an array with elements 5,8,9,6 since they are all greater than or equal to 5.

How would I preform this? the algorithm is easy, but I don't understand how we take in that condition.

Thank you.

Upvotes: 0

Views: 130

Answers (3)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

The idiomatic way would be:

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

More info on Enumerator::Lazy#enum_for.

Upvotes: 2

Ursus
Ursus

Reputation: 30071

I take for granted you don't want to use select method or similar but you want to understand how blocks work.

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

Upvotes: 3

Poilon
Poilon

Reputation: 184

you can do

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

then call

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

but instead you can just call select with a block directly :)

Upvotes: 0

Related Questions