Blog Archive

Thursday, June 22

Ruby and C#

Ruby

numbers = [1, 2, 3, 4, 5]
is_even = proc { |n| (n.modulo 2).zero? }

(numbers.map {|n| "#{n} #{is_even[n] ? 'is' : 'is not'} even"}).each {|summary| puts summary}

C# 3.0

int[] numbers = {1, 2, 3, 4, 5};
Predicate<int> isEven = n => n % 2 == 0;

Array.ForEach(numbers, n => Console.WriteLine("{0} {1} even", n, isEven(n) ? "is" : "is not"));

or if you prefer...

Array.ForEach(numbers, n => Console.WriteLine("{0} {1} even", n, isEven(n) ? "is" : "is not"));

numbers.Each(n => Console.WriteLine("{0} {1} even", n, isEven(n) ? "is" : "is not"));


// elsewhere
public static class EnumerableExtensions
{
  public static void Each<T>(this IEnumerable<T> collection, Action<T> action)
  {
    foreach (T item in collection)
      action(item);
  }
}

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.