[Ruby] Meaning of &. How to avoid the error when the receiver (object) is nil

This is a personal memo.

About the role of & .. Add & before the dot in the process of executing the method on a normal object (receiver).

Syntax and role

ยท Receiver & .method

** Returns nil instead of error if the receiver is nil **.

Illustration

Normal processing (error)


x = nil
x.length

=> NoMethodError (undefined method `length' for nil:NilClass)

&.Method


x = nil
x&.length

=> nil

It can return nil without error.

Processing with default values

The to_s method that converts to a string and the to_i method that converts to a number will default to the default value instead of an error if there is no receiver.

However, using & . returns nil when the receiver is nil.

Normal


x = nil
x.to_s
=> ""

x.to_i
=> 0 

&.


x = nil
x&.to_s
=> nil

x&.to_i
=> nil 

Practical

On a practical basis, if the receiver could be nil, it returns nil instead of an error display, in which case||Returns the value set by default in.

Example 1


x =nil
x&.lenght || 0

=> 0

Example 1


x =nil
x&.lenght ||  "is nil"

=> "is nil"

You can simply write like exception handling.

Recommended Posts

[Ruby] Meaning of &. How to avoid the error when the receiver (object) is nil
[Ruby] How to prevent errors when nil is included in the operation
[Ruby on Rails] How to Japaneseize the error message of Form object (ActiveModel)
[swift] How to control the behavior when the back button of NavigationBar is pressed
[Ruby] How to find the sum of each digit
How is the next value of the Time object correct?
The idea of cutting off when the error is not resolved
[Ruby] How to retrieve the contents of a double hash
What is an immutable object? [Explanation of how to make]
[Ruby] Thinking when there is no receiver in front of the method (it looks like)
Want to know what Ruby n is the power of 2? (Power judgment of 2)
How to output the value when there is an array in the array
How to solve the unknown error when using slf4j in Java
How to write the view when Vue is introduced in Rails?
I want to make the frame of the text box red when there is an input error
[Rails] About the error when displaying the screen due to the autofocus of the form
How to determine the number of parallels
Error when the member of Entity class used in SpringWebFlux is final
[Docker] How to build when the source code is bind-mounted on the container
How to find the total number of pages when paging in Java
How to sort the List of SelectItem
How to constrain the action of the transition destination when not logged in
How to solve the local environment construction of Ruby on Rails (MAC)!
Android development, how to check null in the value of JSON object
[Ruby On Rails] How to search the contents of params using include?
[Rails] What to do when the Refile image is not displayed when writing the processing at the time of Routing Error
How to resolve the error'ActionView :: Template :: Error (The asset "application.css" is not present in the asset pipeline.'" When precompiling Rails assets
[Note] [Beginner] How to write when changing the value of an array element in a Ruby iterative statement
Possibility when deploying to EC2 but nothing is displayed in the error log
[Promotion of Ruby comprehension (1)] When switching from Java to Ruby, first understand the difference.
How to resolve the "OpenSSH keys only supported if ED25519 is available" error
[Laravel] How to deal with out of memory error when composer require [Docker]
[Ruby on Rails] Rails tutorial Chapter 14 Summary of how to implement the status feed
[Heroku] How to solve when an error is displayed on git push heroku master
How to set when "The constructor Empty () is not visible" occurs in junit
[Ruby on Rails] How to display error messages
Customize how to divide the contents of Recyclerview
The story of introducing Ajax communication to ruby
[Ruby] "Reference to object" and "Contents of variable"
How to get today's day of the week
How to delete the database when recreating the application
Output of how to use the slice method
[Ruby] Code to display the day of the week
How to display the result of form input
How to build the simplest blockchain in Ruby
[Java] How to get the authority of the folder
[Ruby basics] How to use the slice method
[Ruby] How to use the map method. How to process the value of an object and get it by hash or symbol.
After installing'devise''bootstrap' of gemfile with rails, what to do when url is an error
Offline real-time how to write Implementation example of the problem in E05 (ruby, C11)
How to get the class name of the argument of LoggerFactory.getLogger when using SLF4J in Java
How to request by passing an array to the query with HTTP Client of Ruby
[ruby] How to assign a value to a hash by referring to the value and key of another hash
Library not loaded when trying to upgrade the version of ruby and rails s
How to fix the problem that the upper half is cut off when using UITabBar
[Rails] How to solve the error "undefined method` visit'" when using Capybara with Rspec
How to identify the cause when GC occurs frequently and CPU usage is high
Summary of how to use the proxy set in IE when connecting with Java
[Java] How to get the URL of the transition source
How to delete / update the list field of OneToMany
How far is the correct answer to divide the process?