View Problem

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five], fetch the third element ('Three')
DiskEdit
ruby
list = ['One', 'Two', 'Three', 'Four', 'Five']
list[2]
DiskEdit
ruby
['One', 'Two', 'Three', 'Four', 'Five'].fetch(2)
DiskEdit
ruby
list = ['One', 'Two', 'Three', 'Four', 'Five']
list.at(2)
DiskEdit
ruby
['One', 'Two', 'Three', 'Four', 'Five'][2] # <= note the [2] at end of array
ExpandDiskEdit
erlang
Result = lists:nth(3, List),
ExpandDiskEdit
erlang
Result = element(3, list_to_tuple(List)),
ExpandDiskEdit
erlang
{Left, _} = lists:split(3, List), Result = lists:last(Left),
ExpandDiskEdit
erlang
Result = nth0(2, List),
DiskEdit
csharp .NET 2.0
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
List<string> list = new List<string>(items);
string third = list[2]; // "Three"
DiskEdit
csharp .NET 3.5 + C# 3.0
// Make sure you import the System.Linq namespace.
// This is not the preferred way of indexing if you are using Lists.
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
IEnumerable<string> list = new List<string>(items);
string third = list.ElementAt(2); // Three
ExpandDiskEdit
fsharp
let result = List.nth ["One"; "Two"; "Three"; "Four"; "Five"] 2

Submit a new solution for ruby, erlang, csharp, or fsharp
There are 14 other solutions in additional languages (clojure, cpp, fantom, go ...)