Search
 
SCRIPT & CODE EXAMPLE
 

RUBY

safe navigation Operator in Ruby

Scenario
Imagine you have an account that has an owner and you want to get the owner’s address. If you want to be safe and not risk a nil error, you would write something like the following:

if account && account.owner && account.owner.address
...
end
This is really verbose and annoying to type. ActiveSupport includes the try method which has a similar behaviour (but with few key differences that will be discussed later):

if account.try(:owner).try(:address)
...
end
It accomplishes the same thing - it either returns the address or nil if some value along the chain is nil. The first example may also return false if, for example, the owner is set to false.
Comment

PREVIOUS NEXT
Code Example
Ruby :: FATAL: database does not exist rails 
Ruby :: ruby symbolize_keys 
Ruby :: ruby make chain method 
Ruby :: rails remove column 
Ruby :: function is uninitialized constant ruby 
Ruby :: ruby different ways to run string interpolation 
Ruby :: ruby hash merge 
Ruby :: ruby string to symbol 
Ruby :: ruby boolean variable 
Ruby :: convert to ascii ruby 
Ruby :: singleton class in ruby 
Ruby :: date class to unix timestamp ruby 
Ruby :: super vs super() ruby 
Ruby :: check type in ruby 
Ruby :: rbenv and ruby different versions 
Ruby :: droptable rails 
Ruby :: command to install ruby gems 
Ruby :: ruby get instance variables without accessor 
Ruby :: sendgrid ruby on rails 
Ruby :: rails resources 
Ruby :: ruby function arguments 
Ruby :: rails check if object is new 
Ruby :: what is touch in rails 
Ruby :: pick element from array that is part of params hash 
Ruby :: ruby mine show all blocks 
Ruby :: difference between is_a and kind_of ruby 
Ruby :: comment 
Ruby :: model with array rails 
R :: how to set a column as index r 
R :: Error in value[[3L]](cond) : Package ‘lavaan’ version 0.6.8 cannot be unloaded: 
ADD CONTENT
Topic
Content
Source link
Name
7+9 =