Ruby Silverの勉強をする中で同じ機能のメソッドの問題が結構あったので、
この機会にしっかりとまとめようと思います。
Arrayクラス
map, collect
各要素に処理を施す(非破壊)
p (1..3).map {|n| n * 3 } # => [3, 6, 9]
p (1..3).collect {|n| n * 3 } # => [3, 6, 9]
map!, collect!
map,collecgtの破壊版
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
array.collect! { |item| item * 3 }
p array # => [3, 6, 9, 12, 15, 18, 21, 24, 27]
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
array.map! { |item| item * 3 }
p array # => [3, 6, 9, 12, 15, 18, 21, 24, 27]
size, length
配列の長さを取得
p [1,2,3].size # => 3
p [1,2,3].length # => 3
include?, member?
p [1,2,3].member?(3) # => true
p [1,2,3].include?(4) # => false
unshift, prepend
arr = [1,2,3]
arr.prepend(0)
p arr # => [0, 1, 2, 3]
arr = [1,2,3]
arr.unshift(0)
p arr # => [0, 1, 2, 3]
push, <<
p [1,2,3].push(4) # => [1, 2, 3, 4]
p [1,2,3] << 4 # => [1, 2, 3, 4]
detect, find
p [1,2,3].find {|n| n % 2 == 0} # => 2
p [1,2,3].detect {|n| n % 2 == 0} # => 2
select, find_all
p [1,2,3,4].select {|n| n % 2 == 0} # => [2, 4]
p [1,2,3,4].find_all {|n| n % 2 == 0} # => [2, 4]
p [1,2,3,4].filter {|n| n % 2 == 0} # => [2, 4]
Hashクラス
has_key?, key?, include?, member?
h = { "a" => 0, "b" => 100, "c" => 200, "d" => 300, "e" => 300 }
p h.has_key?("a") #=> true
p h.key?("a") #=> true
p h.include?("z") #=> false
p h.member?("z") #=> false
has_value?, value?
h = { "a" => 0, "b" => 100, "c" => 200, "d" => 300, "e" => 300 }
p h.has_value?(0) # => true
p h.value?(0) # => true
update, merge!
h = { "a" => 0, "b" => 100, "c" => 200, "d" => 300, "e" => 300 }
h.update({"f" => 400})
p h #=> {"a"=>0, "b"=>100, "c"=>200, "d"=>300, "e"=>300, "f"=>400}
h = { "a" => 0, "b" => 100, "c" => 200, "d" => 300, "e" => 300 }
h.merge!({"f" => 400})
p h #=> {"a"=>0, "b"=>100, "c"=>200, "d"=>300, "e"=>300, "f"=>400}