Flowdock

Notes posted by l3x

RSS feed
September 27, 2013
0 thanks

Using find_index to return first match. Profit!

This example shows how to use find_index to return a result as soon as the first occurrence of what you are looking for is found.

Code example

class Widget < Struct.new(:name, :profit); end

class WidgetManager
  def initialize(*widgets)
    @widgets = widgets
  end
  def is_any_widget_profitable?
    @widgets.find_index { |w| w.profit > 0 }  # <== usage!
  end
end

wm = WidgetManager.new(Widget.new('a', -100), Widget.new('b', 200), Widget.new('c', 300))
wm.is_any_widget_profitable?  # => 1
(wm.is_any_widget_profitable?) ? 'some profit' : 'all loss'  # => "some profit"

wm = WidgetManager.new(Widget.new('a', -100), Widget.new('b', -200), Widget.new('c', -300))
wm.is_any_widget_profitable?  # => nil
(wm.is_any_widget_profitable?) ? 'some profit' : 'all loss'  # => "all loss"