LoginSignup
6
1

More than 5 years have passed since last update.

みなさま、食後のrubyクイズでございます。

Last updated at Posted at 2017-06-14

みなさま、食後のrubyクイズでございます:ice_cream:

問題

第1問

:hoge.size
# => ?

第2問

!true
# => ?

! true
# => ?

第3問

[3,4,5].map do |hoge|
     next hoge if hoge>4
end
# => ?

array = [3,4,5]
array.map do |hoge|
     next hoge if hoge>4
end
puts array

# => ?

.
.
.
.
.
.

答え

第1問

:hoge.size
# => 4

シンボルをsizeにしたら、文字数が返ってきます:innocent:

第2問

!true
# => false

! true
# => false

!trueは演算子の"!"でtrueがfalseになり、
! trueはメソッドの"!"でtrueがfalseになります。
! trueはメソッドの"!"を使える」と思っていたのですが、どうやら違うみたいです。
なぜスペース空けてもできるのか、鋭意調べ中でございます。少々お待ちください:moyai:
とりあえず、スペース空けてもfalseになるよとだけ。

第3問

[3,4,5].map do |hoge|
     next hoge if hoge>4
end
# => [nil, nil, 5]

array = [3,4,5]
array.map do |hoge|
     next hoge if hoge>4
end
puts array

# => [3, 4, 5]

mapは返り値がないとnilになってしまいます。
そして、mapは元の配列には影響を与えません。
レシーバの配列を変更したい場合はmap!を使いましょう。

array = [3,4,5]
array.map!{|hoge| next hoge if hoge>4}
array

# => [nil, nil, 5]

みなみなさま

Have a nice day ! :innocent:

6
1
2

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
6
1