Search
 
SCRIPT & CODE EXAMPLE
 

RUBY

ruby ||=

# a ||= b is a conditional assignment operator. It means:
# if a is undefined or falsey, then evaluate b and set a to the result.
# otherwise (if a is defined and evaluates to truthy), then b is not evaluated, and no assignment takes place.

a ||= nil      # => nil
a ||= 0        # => 0
a ||= 2        # => 0

# It can be useful in some memoization scenarios
def current_user
  @current_user ||= User.find_by_id(session[:user_id])
end

# it can be problematic with boolean values

foo = false 	# => false
foo ||= true 	# => true      <-- false have been a valid value 
foo ||= false 	# => true

# Send an email to the user (unintended bugs when used with boolean values)
#
# @param [String] use_ses - use AWS SES to send the email.
#                           when testing locally, set this value to false
def send_email(use_ses = nil)
  use_ses ||= true

  puts 'email sent successfully' if use_ses
end

send_email
# => email sent successfully

send_email(true)
# => email sent successfully

send_email(false)
# This is a bug
# => email sent successfully
Comment

ruby |=

# When working with arrays |= is useful for uniquely appending to an array.
>> x = [1,2,3]
>> y = [3,4,5]

>> x |= y
>> x
=> [1, 2, 3, 4, 5]
Comment

ruby &:

ar.map { |element| element.reverse }
Comment

||= ruby

a ||= nil
a ||= 0
a ||= 2
# a returns 0
# ||= conditional assignment if a is unassigned then it gets assigned
# otherwise it remains with the value it has as per 2 and 3 lines
Comment

ruby &:

ar.map(&:reverse)
Comment

PREVIOUS NEXT
Code Example
Ruby :: rails humanize date 
Ruby :: how to unloack user devise rails 
Ruby :: rails class note reminders 
Ruby :: ruby rails check field changed 
Ruby :: EOFError: end of file reached 
Ruby :: JSON.parse prevent error ruby 
Ruby :: run bundle without production in rails 
Ruby :: ruby null 
Ruby :: rails check test database 
Ruby :: location of a string ruby 
Ruby :: how to know current schema database in rails 
Ruby :: rails .map unless nil 
Ruby :: how to group array in ruby 
Ruby :: apple calendar gem in rails 
Ruby :: rails rspec test email sent 
Ruby :: hoow to match a complete word in ruby? 
Ruby :: redis localhost url 
R :: drop columns by index r 
R :: i have library(dplyr) but i still get Error in select(., 
R :: r convert matrix to list of column vectors 
R :: types of vectors in r 
R :: how to build random forest in r 
R :: remove row from matrix r 
R :: convert a datetime to date r 
R :: r function syntax 
R :: R language get all columns in a dataset 
R :: ggplot categorical data r 
R :: generate pair with one same variable in r 
R :: str_extract all using mutate and toString 
R :: gsub function r 
ADD CONTENT
Topic
Content
Source link
Name
5+8 =