LoginSignup
4
0

More than 5 years have passed since last update.

Rails Tutorial 4章メモ

Posted at

●4.3 配列と範囲演算子

・文字列⇒配列変換

文字列.split(区切り文字)
※区切り文字のデフォルトはスペース

・配列の要素にアクセス

a[数字]
a[-1]で最後の要素
a.first,a.second,a.third.....

・配列に対するメソッド

要素が含まれているか?

⇒a.include?(要素)

要素をソート

⇒a.sort

並びを逆に

⇒a.reverse

並びをシャッフル

⇒a.shuffle
※a.shuffle[0..7]にするとシャッフルしてから冒頭の8文字のみ返す

配列に対するメソッドをa自身に適用したい場合(破壊的メソッド)

⇒a.sort!

・要素を配列に追加

a.push(要素)
a << 要素

・範囲オブジェクトを返す

(0..9).to_a

繰り返し処理

数値の繰り返し

範囲オブジェクト.each |i| do
-繰り返す式
end

繰り返す回数を指定する場合

数字.times{繰り返す式}

文字列等、範囲オブジェクトの各要素に対して適用する繰り返し

[A B C].map{|char| char.downcase}
⇒["a","b","c"]

ハッシュとシンボル

ハッシュの定義

user = {} #空のハッシュ
user["first_name"] = "Michael" #first_nameをキーに、値がMichael
user["last_name"] = "Hartl" #last_nameをキーにHartlが値

シンボルを使ったまとめた定義

h2 = { name: "Michael Hartl", email: "michael@example.com" }

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