This applies equally to ElementAt. Not that there’s much to translate here, but it’s a noteworthy language feature that Ruby arrays return nil when you go out of range.
LINQ: ElementAtOrDefault
Returns the element at a specified index in a sequence or a default value if the index is out of range.
string[] names = { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu" }; int index = 20; string name = names.ElementAtOrDefault(index); Console.WriteLine( "The name chosen at index {0} is '{1}'.", index, String.IsNullOrEmpty(name) ? "<no name at this index>" : name); /* This code produces the following output: The name chosen at index 20 is '<no name at this index>'. */ |
Ruby: at(index) → obj or nil
Returns the element at index. A negative index counts from the end of self. Returns nil if the index is out of range. See also Array#[].
names = ["Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu"] index = 20 value = names.at(index) puts "The name chosen at index #{index} is " + (value == nil ? "<no value at this index>" : value) |