0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Ruby】エイリアスメソッドについてのまとめ_Ruby Silver対策

Last updated at Posted at 2024-07-16

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}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?