Feeds:
Posts
Comments

Archive for the ‘Ruby’ Category

To sort a set of elements that implement IComparable with Linq use OrderBy

	var words = new[] { "Perl", "c#", "ruby", "java" };

	var ordered = words
		.OrderBy(x => x);

	ordered.ToList().ForEach(Console.WriteLine);

Note that the default sort ignores case.

output:

c#
java
Perl
ruby

The Ruby equivalent is sort

	words = [ "Perl", "c#", "ruby", "java" ]
	
	ordered = words
		.sort

	puts ordered

Note that the default sort respects case.

output:

Perl
c#
java
ruby

To sort a set of elements that do not implement IComparable, or based on a characteristic with Linq use OrderBy

	var types = new[] { "c#".GetType(), true.GetType(), 1.GetType() };

	var ordered = types
		.OrderBy(x => x.Name);

	ordered.ToList().ForEach(Console.WriteLine);

output:

System.Boolean
System.Int32
System.String

The Ruby equivalents are sort

	types = [ "c#".class, true.class, 1.class ]
	
	ordered = types
		.sort{|a,b| a.name <=> b.name}

	puts ordered

and sort_by

	types = [ "c#".class, true.class, 1.class ]
	
	ordered = types
		.sort_by{|x| x.name}

	puts ordered

Both Ruby options output:

Fixnum
String
TrueClass

Linq methods:

All Any Count First FirstOrDefault GroupBy Max OrderBy Select Single
Skip SkipWhile Where

Advertisements

Read Full Post »

To determine whether there is only one element in a set with Linq use Single

	var oneWord = new string[] { "bear" };

	var match = oneWord
		.Single();

	Console.WriteLine(match);

	var nullWords = new string[] { null };

	var nullMatch = nullWords
		.Single();

	Console.WriteLine(nullMatch == null);

	var words = new[] { "java", "c#", "ruby" };

	var multiple = words
		.Single();  // <-- throws InvalidOperationException

	var noWords = new string[] { };

	var none = noWords
		.Single();  // <-- throws InvalidOperationException

Single returns the matching element if there is only one. Note that an input containing one null matches Single

output:

bear
True

The closest Ruby equivalent is one? which returns a boolean.

	one_word = ["bear"]
	
	match = one_word
		.one?

	nil_words = [nil]

	nil_match = nil_words
		.one?
		
	words = ["java", "c#", "ruby"]

	multiple = words
		.one?

	no_words = []
		
	none = no_words
		.one?

	puts match, nil_match, multiple, none

Note that an input containing a single nil does not match one?

output:

true
false
false
false

To determine whether only one element of a set matches a condition with Linq use Single

	var words = new[] { "java", "c#", "ruby" };

	var match = words
		.Single(x => x.Length == 2);

	Console.WriteLine(match);

	var nullWords = new string[] { null };

	var nullMatch = nullWords
		.Single(x => x == null);

	Console.WriteLine(nullMatch == null);
	
	var multiple = words
		.Single(x => x.Length == 4); // <-- throws InvalidOperationException
		
	var none = words
		.Single(x => x.Length > 10); // <-- throws InvalidOperationException

Single returns the matching element if there is only one.

output:

c#
True

The closest Ruby equivalent is one? which returns a boolean.

	words = ["java", "c#", "ruby"]

	match = words
		.one?{|x| x.length == 2}

	multiple = words
		.one?{|x| x.length == 4}

	none = words
		.one?{|x| x.length > 10}

	nil_word = [nil]

	nil_match = nil_word
		.one?{|x| x == nil}
		
	puts match, multiple, none, nil_match

output:

true
false
false
true

Linq methods:

All Any Count First FirstOrDefault GroupBy Max OrderBy Select Single
Skip SkipWhile Where

Read Full Post »

To find the element of a set that has the last/highest sort value (for elements that implement IComparable) with Linq use Max

	var words = new[] { "a", "cow", "bell" };

	var maxWord = words.Max();

	var ints = new[] { 4, 1, 5, 3, 2 };

	var maxInt = ints.Max();

	Console.WriteLine(maxWord);
	Console.WriteLine(maxInt);

output:

cow
5

The Ruby equivalent is max

	words = ["a", "cow", "bell"]

	max_word = words
		.max
	
	ints = [4, 1, 5, 3, 2]

	max_int = ints
		.max
	  
	puts max_word, max_int

output:

cow
5

To find the element of a set that has the last/highest sort value (for elements that do not implement IComparable) with Linq use Max and a lambda to indicate how to compare the elements.

	var types = new[] { typeof(string), typeof(int) };

	var max = types.Max(x => x.Name);

	Console.WriteLine(max);

output:

String

The Ruby equivalents are max

	types = ["a".class, 1.class]

	max = types
		.max{|a,b| a.name <=> b.name }
	
	puts max

and max_by

	types = ["a".class, 1.class]

	max = types
		.max_by{|a| a.name }
	
	puts max

Both Ruby options output:

String

Linq methods:

All Any Count First FirstOrDefault GroupBy Max Select Skip SkipWhile Where

Read Full Post »

To group elements of a set based on some characteristic with Linq use GroupBy

	var ints = new[] { 1, 2, 3, 4, 5 };

	var groups = ints
		.GroupBy(x => x % 2);

	foreach (var group in groups)
	{
		var strings = group.Select(i => i.ToString()).ToArray();
		string joined = String.Join(", ", strings);
        Console.WriteLine("key {0} has values {1}", group.Key, joined);
	}

output:

key 1 has values 1, 3, 5
key 0 has values 2, 4

The Ruby equivalent is group_by

	ints = [1, 2, 3, 4, 5]

	groups = ints
		.group_by{|x| x % 2}

	groups.each{|group| puts "key #{group[0]} has values #{group[1]}"}

output:

key 1 has values [1, 3, 5]
key 0 has values [2, 4]

Linq methods:

All Any Count First FirstOrDefault GroupBy Max Select Skip SkipWhile Where

Read Full Post »

To split a set into groups of size N with C# you have to write a custom method like the following extension method

public static class IEnumerableExtensions
{
	public static IEnumerable<List<T>> InSetsOf<T>(
		this IEnumerable<T> source, int max)
	{
		var toReturn = new List<T>(max);
		foreach (T item in source)
		{
			toReturn.Add(item);
			if (toReturn.Count == max)
			{
				yield return toReturn;
				toReturn = new List<T>(max);
			}
		}
		if (toReturn.Any())
		{
			yield return toReturn;
		}
	}
}

with usage:

	var ints = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	
	var sets = ints
		.InSetsOf(3);
	
        foreach (var set in sets)
        {
            var strings = set.Select(i => i.ToString()).ToArray();
            string joined = String.Join(", ", strings);
            Console.WriteLine(joined);
        }

output:

1, 2, 3
4, 5, 6
7, 8, 9
10

The Ruby equivalent is a built-in function named each_slice

	ints = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

	sets = ints
		.each_slice(3)

	sets.each{|s| p s}

output:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10]

Read Full Post »

To skip over elements of a set until a condition is met with Linq use SkipWhile

	var ints = new[] { -2, -1, 0, 1, 2, 3 };

	var positives = ints
		.SkipWhile(x => x < 1);

	positives.ToList().ForEach(Console.WriteLine);

output:

1
2
3

The Ruby equivalent is drop_while

	ints = [-2, -1, 0, 1, 2, 3]

	positives = ints
		.drop_while{|x| x < 1}

	puts positives

output:

1
2
3

Linq methods:

All Any Count First FirstOrDefault GroupBy Max Select Skip SkipWhile Where

Read Full Post »

To skip over the first N elements of a set with Linq use Skip

	var ints = new[] { -1, 0, 1, 2, 3 };

	var positives = ints
		.Skip(2);

	positives.ToList().ForEach(Console.WriteLine);

output:

1
2
3

The Ruby equivalent is drop

	ints = [-1, 0, 1, 2, 3]

	positives = ints
		.drop(2)

	puts positives

output:

1
2
3

Linq methods:

All Any Count First FirstOrDefault GroupBy Max Select Skip SkipWhile Where

Read Full Post »

Older Posts »

%d bloggers like this: