Creating a Range in Ruby is dead simple.
1: my_range = (1..10)
2:
3: my_range.each { |i| puts "My number is: #{i}." }
Running that little snippet will do just what you think, push the numbers 1 through 10 out and shove them into the sentence my number is x.
1: My number is: 1.
2: My number is: 2.
3: My number is: 3.
4: My number is: 4.
5: My number is: 5.
6: My number is: 6.
7: My number is: 7.
8: My number is: 8.
9: My number is: 9.
10: My number is: 10.
This code isn't all that useful as is, but being able to concisely construct a range can be very useful. Ranges often come in handy when writing unit tests, making lists, and a number of other places.
And in F# too...
Many, maybe even all... I didn't check :), functional language also provide a convenient way to build a range. F# is no exception and its syntax looks a lot like Ruby's.
1: myRange = {1 .. 10} // this is just an IEnumerable<int>
If you're interested in learning more about F#, check out Dustin Campbell's excellent series on why he loves F#.
And what about C#?
Too bad we don't have such a nice, concise syntax in C#, huh?
Yeah, too bad. But as of C# 3.0 we do have something close, the Enumerable class!
1: IEnumerable<int> myRange = Enumerable.Range(1, 10);
2:
3: IEnumerable<IWidget> mySequence = Enumerable.Repeat(someWidget, 10);
Note: Enumerable actually lives in the System.Linq namespace.
No, its not quite as concise as the Ruby or F# examples above, but it is a heck of a lot better than having to write some kind of loop to build up the range.
In line #1 we're saying we want a Range that starts at 1 and has a length of 10. That is, it contains the values 1 through 10... just like we'd expect.
Oh, and line #3 isn't really a Range, its called a Sequence. In this case mySequence is some kind of IEnumerable with one object repeated 10 times.
Don't you just love finding little nuggets that can turn mundane code into trivially simple code. Enjoy!
Technorati Tags:
c#,
ruby,
f#,
range