看到有这样的代码 @user_info&.user_mobile
不理解 &.
的作用是什么
ruby 2.3 引入的安全调用运算符
# Ruby <= 2.2.x
if user && user.admin?
# do something
end
# Ruby 2.3
if user&.admin?
# do something
end
account = Account.new(owner: nil) # account without an owner
account.owner.address
# => NoMethodError: undefined method `address' for nil:NilClass
account && account.owner && account.owner.address
# => nil
account.try(:owner).try(:address)
# => nil
account&.owner&.address
# => nil
account = Account.new(owner: false)
account.owner.address
# => NoMethodError: undefined method `address' for false:FalseClass `
account && account.owner && account.owner.address
# => false
account.try(:owner).try(:address)
# => nil
account&.owner&.address
# => undefined method `address' for false:FalseClass`
account = Account.new(owner: Object.new)
account.owner.address
# => NoMethodError: undefined method `address' for #<Object:0x00559996b5bde8>
account && account.owner && account.owner.address
# => NoMethodError: undefined method `address' for #<Object:0x00559996b5bde8>`
account.try(:owner).try(:address)
# => nil
account&.owner&.address
# => NoMethodError: undefined method `address' for #<Object:0x00559996b5bde8>`
# There's a stricter version of try - try! for you:
account.try!(:owner).try!(:address)
# => NoMethodError: undefined method `address' for #<Object:0x00559996b5bde8>`
&. try 基本上用途都是对付对 nil 对象。a.b.c 这样的火车是 nil 的老窝。 代码中频繁出现 a.b.c.method, 违反 Demeter law. 我觉得需要认真思考类设计,并适当包装。 &. 和 try 在代码中到处出现的时候,可以用 null object 来解决很大一部分。