Jeff Nyman
Jeff Nyman

Reputation: 890

Building up an Intuition for Using Inject in Ruby

I'm trying to understand how and when to recognize that inject/reduce is more useful in Ruby code. So, for example, I know I can take this:

def add(numbers)
  sum = 0
  numbers.each { |n| sum += n }
  sum
end

That can be "reduced" to:

numbers.inject(0) { |sum, n| sum += n }

What I don't see, however, is how that works when you have a slightly more complicated expression. Here's what I'm wrestling with:

def process_data(condition, data)
  condition.each do |key, value|
    data = method("query_#{key}").call(data, value)
  end
  data
end

One of the problems is that I'm variable shadowing with data but I still struggle to find a way to treat this as something I'm injecting.

Is there a way people have found to turn this idiom into a heuristic that you can easily follow? It's these kinds of things that I feel I struggle with in Ruby, spending more time trying to be idiomatic Ruby.

So I guess perhaps my better question is this: is the process_data method that I show one that should be refactored to use reduce/inject to be idiomatic Ruby?

Upvotes: 2

Views: 49

Answers (1)

jazzytomato
jazzytomato

Reputation: 7214

What about that ?

def process_data(condition, data)
  condition.reduce(data) { |data, (key,value)| method("query_#{key}").call(data, value) }
end

Upvotes: 2

Related Questions