0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Ruby 配列 ブロックについて 2

Last updated at Posted at 2023-07-14

はじめに

学習内容

配列(Arrayクラス)
  • 要素の選択や追加
  • 集合

参考にした教材

配列(Arrayクラス)

a = [1, 2, 3, 4, 5]
変数aの配列の2つ目の要素から2つ分の要素を取り出したいとき

配列[位置, 取得する長さ]

a = [1, 2, 3, 4, 5]

puts a[1, 2] => 2, 3
変数aの配列の1つ目、3つ目の要素を選択して取り出したいとき

values_atメソッド 取得したい要素の添字を複数指定

a = [1, 2, 3, 4, 5]

puts a.values_at(0, 2) => 1, 3
変数aの配列の最後の要素を取り出したいとき(メソッドなし)
a = [1, 2, 3, 4, 5]

puts a[-1] => 5
変数aの配列の最後の要素を取り出したいとき(メソッドあり)

lastメソッド 配列の最後の要素を取得

a = [1, 2, 3, 4, 5]

puts a.last => 5
変数aの配列の最後の要素から3つを取り出したいとき

lastメソッド 配列の最後の要素を取得

a = [1, 2, 3, 4, 5]

puts a.last(3) => 3, 4, 5
b = []
変数bに1,10,100を追加したいとき

pushメソッド 配列に要素を追加

b = []

puts b.push(1, 10, 100) => 1, 10, 100
array = [1]
other = [2, 3]
変数arrayと変数otherの配列を連結したいとき(破壊的)

concatメソッド 「concat(other)」で配列otherを自身の末尾に破壊的に連結

array = [1]
other = [2, 3]

puts array.concat(other) => 1, 2, 3
変数arrayと変数otherの配列を連結したいとき(破壊的でない)
array = [1]
other = [2, 3]

linking = array + other
puts linking  => 1, 2, 3

# 参考
puts array => 1
puts other => 2, 3
a = ["カレー", "ラーメン", "寿司"]
b = ["ステーキ", "寿司", "パエリア"]
変数aと変数bの和集合
a = ["カレー", "ラーメン", "寿司"]
b = ["ステーキ", "寿司", "パエリア"]

puts a | b => カレー, ラーメン, 寿司, ステーキ, パエリア
変数aと変数bの差集合(aからbを取り除く)
a = ["カレー", "ラーメン", "寿司"]
b = ["ステーキ", "寿司", "パエリア"]

puts a - b => カレー, ラーメン
変数aと変数bの積集合
a = ["カレー", "ラーメン", "寿司"]
b = ["ステーキ", "寿司", "パエリア"]

puts a & b => 寿司

本格的に集合演算をする場合

配列よりもSetクラスを使う方が望ましいとのこと

require "set"
a = Set["カレー", "ラーメン", "寿司"]
b = Set["ステーキ", "寿司", "パエリア"]

puts a | b => #<Set: {"カレー", "ラーメン", "寿司", "ステーキ", "パエリア"}>
puts a - b => #<Set: {"カレー", "ラーメン"}>
puts a & b => #<Set: {"寿司"}

まとめ

  • 苦手な配列が少しわかってきた気がする
  • 次回はブロックについてまとめたい

⚠️学習4ヶ月目の初学者による投稿です。
⚠️間違いがあるかもしれません。ご容赦ください。
⚠️ご指導、ご教授いただけると幸いです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?