範囲オブジェクト0..16を使って、各要素の2乗を出力する
>> (1..16).map{|i| i**2}
=> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256]
mapメソッドは、渡されたブロックを配列や範囲オブジェクトの各要素に対して適用し、その結果を返します。
('a'..'z').to_a.shuffle[0..7].joinを読み解く
>> ('a'..'z').to_a # 英小文字を列挙した配列を作る
=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
"p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
>> ('a'..'z').to_a.shuffle # シャッフルする
=> ["c", "g", "l", "k", "h", "z", "s", "i", "n", "d", "y", "u", "t", "j", "q",
"b", "r", "o", "f", "e", "w", "v", "m", "a", "x", "p"]
>> ('a'..'z').to_a.shuffle[0..7] # 配列の冒頭8つの要素を取り出す
=> ["f", "w", "i", "a", "h", "p", "c", "x"]
>> ('a'..'z').to_a.shuffle[0..7].join # 取り出した要素を結合して1つの文字列にする
=> "mznpybuj"
mapとupcaseとjoinメソッド
map..上に書いた通り
upcase..小文字の文字を大文字に置き換える
join..上の通り
yeller (大声で叫ぶ) というメソッドを定義
def yeller(row)
row.join.upcase
end
>> def yeller(s)
>> s.map(&:upcase).join
>> end
=> :yeller
>> yeller(['o','l','d'])
=> "OLD"
ランダムな8文字を生成し、文字列として返すメソッド
>> def random_subdomain
>> ('a'..'z').to_a.shuffle[0..7].join
>> end
=> :random_subdomain
>> random_subdomain
=> "wcyerpiq"
文字列をシャッフルするメソッド
>>def string_shuffle(s)
>> s.split('').shuffle.join
>>end
=> :string_shuffle
>>string_shuffle("foobar")
=> "arobof"