Skip to content

Instantly share code, notes, and snippets.

@RobertDober
Created September 8, 2009 14:23
Show Gist options
  • Save RobertDober/182953 to your computer and use it in GitHub Desktop.
Save RobertDober/182953 to your computer and use it in GitHub Desktop.
require 'test/unit'
class Array
def get idx
fetch idx, :undefined
# fonctionne également
# fetch( idx ){ :undefined }, mais cet idiome est plus utile en cas de traitement
# plus complex, et biensur:
# fetch( idx ) raises une exception IndexError si l'élément n'existe pas
# Hash a un #fetch pratiquement identique, il me semble plus connu
end
end
class ArrayAccessTest < Test::Unit::TestCase
def test001
42.times do |i|
assert_equal :undefined, [].get( i )
end
end
def test002
assert_equal 42, [42].get( 0 )
assert_equal :undefined, [42].get( 1 )
end
def test003
assert_equal nil, [nil].get( 0 )
assert_equal :undefined, [nil].get( 1 )
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment