ruby-2.3

Safe navigation operator (&.) for nil

点点圈 提交于 2019-11-27 06:35:51
问题 As Ruby 2.3 introduces the Safe navigation operator( &. ), a.k.a lonely operator, the behavior on nil object seems odd. nil.nil? # => true nil&.nil? # => nil Is that designed to behave like this way? Or some edge case that slipped away when adding the lonely operator? 回答1: foo&.bar is shorthand for foo && foo.bar , so what would you expect the result of the expression nil && nil.nil? to be? 回答2: This is because nil&.nil? is shorthand for nil && nil.nil? . This would evaluate to nil && true ,

What does the comment “frozen_string_literal: true” do?

蓝咒 提交于 2019-11-26 22:30:37
问题 This is the rspec binstub in my project directory. #!/usr/bin/env ruby begin load File.expand_path("../spring", __FILE__) rescue LoadError end # frozen_string_literal: true # # This file was generated by Bundler. # # The application 'rspec' is installed as part of a gem, and # this file is here to facilitate running it. # require "pathname" ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", Pathname.new(__FILE__).realpath) require "rubygems" require "bundler/setup" load Gem.bin_path(

What does &. (ampersand dot) mean in Ruby?

僤鯓⒐⒋嵵緔 提交于 2019-11-26 19:46:14
I came across this line of ruby code. What does &. mean in this? @object&.method It is called the Safe Navigation Operator. Introduced in Ruby 2.3.0, it lets you call methods on objects without worrying that the object may be nil (Avoiding an undefined method for nil:NilClass error), similar to the try method in Rails . So you can write @person&.spouse&.name instead of @person.spouse.name if @person && @person.spouse From the Docs : my_object.my_method This sends the my_method message to my_object. Any object can be a receiver but depending on the method's visibility sending a message may

What does &. (ampersand dot) mean in Ruby?

不想你离开。 提交于 2019-11-26 07:24:15
问题 I came across this line of ruby code. What does &. mean in this? @object&.method 回答1: It is called the Safe Navigation Operator. Introduced in Ruby 2.3.0, it lets you call methods on objects without worrying that the object may be nil (Avoiding an undefined method for nil:NilClass error), similar to the try method in Rails. So you can write @person&.spouse&.name instead of @person.spouse.name if @person && @person.spouse From the Docs: my_object.my_method This sends the my_method message to