Learned idioms

||=Self-substitution using

x ||=If you look at the code for A, interpret it as "if the variable X is nil or false, assign A to X"

python


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

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

In the same way that n + = 1 can be expanded to n = n + 1

python


number ||= 10
number = number || 10
#It has the same meaning.

Type conversion of boolean value using !!

!! Is a negative operator Example If you write! A A is true-> false false or nil-> true

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

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

Example of use

python


def title_exists?
  #Search for the title from the database etc. (if not nil)
  title = find_title
  if title
    true
  else
    false
  end
end

python


def title_exists?
  !!find_title
end

References An introduction to Ruby for those who want to become professionals

Recommended Posts

Learned idioms
What i learned