Search
 
SCRIPT & CODE EXAMPLE
 

RUBY

conditional assignment operator 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

conditional operator in ruby

#condition ? true : false
apple_stock > 1 ? :eat_apple : :buy_apple
<div class="open_grepper_editor" title="Edit & Save To Grepper"></div>
Comment

Ruby conditionals

is_student = false
is_smart =false

if is_student and is_smart
	puts "you are a smart student
elsif is_student and !is_smart
	puts "You are not a smart student"
else
	puts "Not a student and not smart"
end

if 1 > 3 
	puts "Number comparison is True"
end
Comment

PREVIOUS NEXT
Code Example
Ruby :: method delete rails not working 
Ruby :: auto load path rails 
Ruby :: ruby match word in string 
Ruby :: rails hidden field default value 
Ruby :: ruby write csv file 
Ruby :: ruby csv parse 
Ruby :: shopify: how to show percentage discount saved 
Ruby :: rails render partial 
Ruby :: ruby loop each with index 
Ruby :: save to csv ruby 
Ruby :: rails setup test db 
Ruby :: How To Set Up Ruby on Rails with Postgres 
Ruby :: create_enum in rails 7 
Ruby :: dictionary ruby 
Ruby :: command to install ruby gems 
Ruby :: create table index unique rails 
Ruby :: rails optional reference 
Ruby :: ruby check if hash has method before calling it 
Ruby :: ruby array loop 
Ruby :: ruby add coma to array of string 
Ruby :: how to unloack user devise rails 
Ruby :: sidekiq configuration file 
Ruby :: add two numbers ruby 
Ruby :: include? reverse ruby 
Ruby :: ruby classes 
Ruby :: call api in ruby 
Ruby :: what is ruby 
R :: how to count the true values in r 
R :: how to transform days in years R 
R :: pi in r 
ADD CONTENT
Topic
Content
Source link
Name
2+2 =