Ruby tip: while becomes any?

Posted by admin on Feb 26, 2010 in Rails, Ruby |

In implementing a new feature in a Rails project, I found myself needing to iterate through an array of patterns looking for a match against a particular string.  In a C-based language or Java, you would probably do something like this:

class LoopDemo
{
  public static void main(String[] args)
  {
    String matchMe = "diamonds";
    String suits[] = {"spades", "clubs", "diamonds", "hearts"};

    boolean found = false;
    int suitIndex = 0;
    while ((!found) && (suitIndex < suits.length))
    {
      found = matchMe.equals(suits[suitIndex++]);
    }

    System.out.println(found ? "Match found" : "Match not found");
  }
}

Ruby, of course, provides a much more compact way of accomplishing exactly the same thing:

match_me = "diamonds"
suits = ["spades", "clubs", "diamonds", "hearts"]

found = suits.any? {|suit| suit == match_me}

puts found ? "Match found" : "Match not found"

Yes, any? stops when it reaches the first returned true value.

The example is contrived — of course, there are easier ways with Ruby to find out if an array contains a particular string. But imagine that your criteria for “finding” or “matching” something is more complex. You can use this approach with an arbitrary amount of complexity in the block being passed into any? as long as the return value from the block evaluates to true or false.

Comments are closed.

Copyright © 2017 Standalone Code LLC All rights reserved. Theme by Laptop Geek.