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
java
String result = list.get(2);
DiskEdit
perl
qw(One Two Three Four Five)[2];
DiskEdit
perl
@list = qw(One Two Three Four Five);
$list[2];
ExpandDiskEdit
groovy 1.0+
list = ['One', 'Two', 'Three', 'Four', 'Five']
result = list[2] // index starts at 0
ExpandDiskEdit
scala
val result = list(2)
DiskEdit
python
list = ['One', 'Two', 'Three', 'Four', 'Five']
list[2]
ExpandDiskEdit
cpp C++/CLI .NET 2.0
String^ result = list[2];
ExpandDiskEdit
fsharp
let result = List.nth ["One"; "Two"; "Three"; "Four"; "Five"] 2
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
ocaml
let third = List.nth [ "One"; "Two"; "Three"; "Four"; "Five" ] 3;;
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
php
$list = array("One", "Two", "Three", "Four", "Five");
$three = $list[2];
DiskEdit
haskell
let a = [1..5]
let b = a !! 2
print b
DiskEdit
clojure
(nth '[One Two Three Four Five] 2)
ExpandDiskEdit
fantom
["One", "Two", "Three", "Four", "Five"][2]
ExpandDiskEdit
fantom
["One", "Two", "Three", "Four", "Five"].get(2)
ExpandDiskEdit
go
fmt.Println(list[2])

Submit a new solution for ruby, java, perl, groovy ...