LoginSignup
14
13

More than 5 years have passed since last update.

[Ruby]配列に対するメソッドまとめ

Last updated at Posted at 2015-01-09

最初にお伝えします。これは私用メモです。
jnchito様のを参考文献として引用させて頂きました。大変勉強になります。

numbers = [1, 2, 3]

find 最初に見つかったものを返す

def find_admin(users)
  users.find(&:admin?)
end
// 1

find_index 要素のインデックスを返す

def find_admin(users)
  users.find_index(&:admin?)
end

select 条件に合うもの全てを返す

def find_admin(users)
  users.select(&:admin?)
end

reject 条件に合わないものを全て返す

def find_admin(users)
  users.reject(&:admin?)
end

count 条件に合う要素の数を返す

def count_admin(users)
  users.count(&:admin?)
end

map ある配列から別の配列を作る

def user_names(users)
  users.map(&:name)
end

compact nil以外の要素を集める

numbers_and_nil = [1, 2, 3, nil, nil, 6]
only_numbers = numbers_and_nil.compact
//[1, 2, 3, 6]

any? 最低でも一つ条件に合う要素があればtrueを返す

def contains_nil?(users)
  users.any?(&:nil?)
end

all? 全ての要素が条件が合っている場合にtrueを返す

def contains_nil(users)
  users.all?(&:nil?)
end

empty? 1件もなければtrueを返す

puts "empty" if users.empty?

first/last 最初と最後の要素を返す

first_user = users.first
last_user = users.last

sample 任意の要素を返す

users.sample

each_with_index eachでループしつつカウンタも同時に取得する

users.each_with_index |user, counter|
  puts ", " if counter > 0
  puts user.name
end

join 配列を1つの文字列として返す

def numbers_text(numbers)
  numbers.join(",")
end
//[1, 2, 3] => "1, 2, 3"

max/max_by 最大の要素を返す

def oldest_user(users)
  users.max_by(&:age)
end

min/min_by 最小の要素を返す

def youngest_user(users)
  users.min_by(&:age)
end

each_with_object ループを回しつつ、別のオブジェクトを組み立ててそれを返す

def admin_names(users)
  users.each_with_object([]) do |user, names|
    names push.user.name if user.admin?
  end
end
14
13
4

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
14
13