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 3 years have passed since last update.

学んだイディオム

Last updated at Posted at 2020-06-03

###||=を使った自己代入
x ||= Aのコードを見たら、「変数Xがnilまたはfalseなら、AをXに代入」と解釈する

number = nil
number ||= 10
number #=> 10

number = 20
number ||= 10
number #=> 20

n += 1 がn=n+1と展開できるのと同じ要領で

number ||= 10
number = number || 10
#同じ意味になる。

###!!を使った真偽値の型変換
!は否定の演算子

 !Aと書いた場合
 Aが真 -> false
 false または nil -> true

!true    #=> false
!!true   #=> true

!!7      #=> true
!!false  #=> false
!!nil    #=> false

使用例

def title_exists?
  #データベースなどからタイトルを探す(なければnil)
  title = find_title
  if title
    true
  else
    false
  end
end
def title_exists?
  !!find_title
end

参考文献
プロを目指す人のためのRuby入門

0
0
1

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?