【Ruby】 配列のおさらい その2

2013年9月10日火曜日

Ruby

t f B! P L
配列の機能をまとめ その2です。

要素を取り出す

human = ["yamada", "tanaka", "ueda"]
puts human.at(1) #=> "tanaka"
puts human.at(-3) #=> "yamada"

配列の要素を1つランダムに返す

human = ["yamada", "tanaka", "ueda"]
puts human.sample #=> "ueda"
puts human.sample(2) #=> ["tanaka", "ueda"]

条件に合う要素を抽出

human = ["yamada", "tanaka", "ueda", "tanaka", "ueda"]
puts human.select {|item| item == "ueda" } #=> ["ueda", "ueda"]

nilの要素を取り除く

human = ["yamada", nil, "tanaka", nil, nil, "ueda"]
puts human.compact #=> ["yamada", "tanaka", "ueda"]

配列の末尾に配列の要素を追加

human = ["yamada", "tanaka", "ueda"]
human.concat(["yabe", "yamada"])
puts human #=> ["yamada", "tanaka", "ueda", "yabe", "yamada"]

配列の要素の数だけブロックを繰り返す

human = ["yamada", "tanaka", "ueda"]
human.cycle(2) {|i| puts "#{i} " }
 #=> "yamada tanaka ueda yamada tanaka ueda"

要素を削除

human = ["yamada", "tanaka", "ueda", "yabe", "jiro"]
human.delete("yamada")
puts human #=> ["tanaka", "ueda", "yabe", "jiro"]

human.delete_at(1)
puts human #=> ["tanaka", "yabe", "jiro"]

Translate

このブログを検索

フォロワー

QooQ