Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@gashiura

Ruby Silverでよく出題される同じ動作をするメソッド群

More than 1 year has passed since last update.

概要

Ruby Silverの勉強をしている時に、同じ動作をするメソッドを問う問題がよく見られたので、分かった範囲でまとめました。

Array

  • map, collect
list = [1, 2, 3, 4, 5, 6]
puts list.map { |r| r * 2 }
# => [2, 4, 6, 8, 10, 12]
puts list.collect { |r| r * 3 }
# => [3, 6, 9, 12, 15, 18]
  • delete_if, reject!
    ブロックに要素を渡し、その評価が真になった要素を全て取り除き、自分自身を返す。
list = [1, 2, 3, 4, 5, 6]
puts list.delete_if { |r| r % 2 == 0 }
# => [1, 3, 5]
puts list.reject! { |r| r % 3 == 0 }
# => [1, 2, 4, 5]

Enumerableモジュール

  • find, detect
    ブロックを評価して、最初に真となる要素を返す。
list = [1, 2, 3, 4, 5, 6]
puts list.find { |r| r % 2 == 0 }
# => 2
puts list.detect { |r| r % 3 == 0 }
# => 3
  • select, find_all
    与えられたブロックを評価した結果の配列を返す。
list = [1, 2, 3, 4, 5, 6]
puts list.select { |r| r % 2 == 0 }
# => [2, 4, 6]
puts list.find_all { |r| r % 3 == 0 }
# => [3, 6]

Hash

  • delete_if, reject!
    ブロックを評価した結果が、真になる値を取り除く。
hash = { 1: 'Ruby', 2: 'PHP', 3: 'Python' }
hash.delete_if { |k, v| k == 1 }
puts hash
# => { 2: 'PHP', 3: 'Python' }

hash = { 1: 'Ruby', 2: 'PHP', 3: 'Python' }
hash.reject! { |k, v| v == 'Python' }
puts hash
# => { 1: 'Ruby', 2: 'PHP' }
  • merge!, update
    自分自身と引数で指定されたハッシュを統合する。
hash = { 1: 'Ruby', 2: 'PHP', 3: 'Python' }
hash.merge!({ 4: 'Java', 5: 'JavaScript' })
puts hash
# => { 1: 'Ruby', 2: 'PHP', 3: 'Python', 4: 'Java', 5: 'JavaScript' }

hash.update({ 6: 'Go' })
puts hash
# => { 1: 'Ruby', 2: 'PHP', 3: 'Python', 4: 'Java', 5: 'JavaScript', 6: 'Go' }
0
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
gashiura
Railsを使用して旅行関係のWebアプリを開発しています。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?