Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a conditional :each in ruby more succinctly?

Tags:

ruby

I'm not sure how to write this code more cleanly in ruby? The only thing that differs is the iterator.

  if items.respond_to?(:find_each)
    items.find_each do |item|
      output_item(csv, item)
    end
  else
    items.each do |item|
      output_item(csv, item)
    end
  end
like image 973
Kamilski81 Avatar asked Mar 10 '26 18:03

Kamilski81


2 Answers

You can use Object#send to call method dynamically:

method = items.respond_to?(:find_each) ? :find_each : :each
items.send(method) do |item|
  output_item(csv, item)
end
like image 134
falsetru Avatar answered Mar 12 '26 09:03

falsetru


I suppose you could do:

method = items.respond_to?(:find_each) ? :find_each : :each
items.send(method) { |item| output_item(csv, item) }
like image 21
moveson Avatar answered Mar 12 '26 08:03

moveson