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 :: how to get ip address of client using rails 
Ruby :: rails crud 
Ruby :: ruby substring remove 
Ruby :: ruby pluck 
Ruby :: auto load path rails 
Ruby :: rails redirect_to with params 
Ruby :: date time string to time in rails 
Ruby :: rails scopes 
Ruby :: ruby remove last element of string 
Ruby :: array to hash ruby 
Ruby :: rails logger info 
Ruby :: how to update a field on after_save rails 
Ruby :: How To Set Up Ruby on Rails with Postgres 
Ruby :: ruby list of files in directory include subfolders 
Ruby :: how to use multiple ruby version in mac as per project 
Ruby :: ruby map hash 
Ruby :: force user to login before action devise rails 
Ruby :: ruby letters order in string 
Ruby :: rails resources 
Ruby :: ruby array with unique values 
Ruby :: ruby sinatra helper 
Ruby :: text_field_tag transfer params rails 
Ruby :: how to create tenant again using Appartment in rails 
Ruby :: comments in ruby grepper 
Ruby :: bundle add cloudinary rails 
Ruby :: sequel not ruby 
Ruby :: allow raise inside rescue rspec 
R :: r delete all variables 
R :: how to append in a list in R 
R :: read csv online r 
ADD CONTENT
Topic
Content
Source link
Name
8+9 =