LoginSignup
3
2

More than 5 years have passed since last update.

Ruby基本文法引っかかりポイント

Last updated at Posted at 2017-07-20

mapとeachの違い

mapはブロックを評価した結果を配列に格納して返してくれる。ブロックがない場合はnilが返る。
それに対し、eachの戻り値はレシーバ自身であり、ブロックの処理を実行するのみ。

map
 [1,2,3].map {|n| n * 5 }
# => [5, 10, 15]
each
 [1,2,3].each {|n| n * 5 }
# => [1, 2, 3]

ブロック内外で変数を参照できるかどうか

for,while,until

構文の中に定義される変数は構文の外側でも参照可能

for
for i in 1..5 do
  sum = 0
  sum += i
end

puts sum

# => 5

times,each,loop

ブロック内に定義した変数はブロックの外側で参照できない
ブロックを引数として受け取れる.

times
5.times do 
    sum = 0
    sum += 1
end

puts sum
# => Main.rb:6:in `<main>': undefined local variable or method `sum' for main:Object (NameError)

配列同士の計算

引き算 -> 重複した要素はすべて取り除かれる
足し算 -> 末尾に追加される

[1,2,3,4]-[1,2]
# => [3, 4]

[1,2,3,4]+[1,2]
# => [1, 2, 3, 4, 1, 2]

マッチング =~

正規表現オブジェクトと文字列オブジェクトのマッチを行う
=~演算子によるマッチングは、最初のマッチした文字の位置を返します。

str = "Enjoy Programming!"
num = str =~ /P/

puts("Pは#{num}文字目にある")
# => Pは6文字目にある
3
2
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
3
2