What does “||=” do in Ruby 1.9.2? [duplicate]

帅比萌擦擦* 提交于 2019-12-17 20:17:03

问题


params[:user][:role_ids] ||= []

What does it do?

ruby -v = 1.9.2p290


回答1:


It assigns [] to params["user][:role_ids] if params["user][:role_ids] is nil or another falsy value...

Otherwise, it retains the original value of params["user][:role_ids]

Example

variable = nil

variable ||= "string"

puts variable # "string"

variable2 = "value"

variable2 ||= "string"

puts variable2 # "value"



回答2:


if params[:user][:role_ids]is nil, it gets initialized with [] otherwise params[:user][:role_ids] holds its value further




回答3:


If the left-hand value is not yet assigned, assign it to the right-hand value. If it is assigned, keep it as itself. A good explanation can be found on Michael Hartl's RoR tutorial site.




回答4:


It's the memoize operator and it does one of two things:

  1. If the value on the left of it is not nil, it simply returns the value
  2. If the value on the left of it is nil (or undefined) it sets it.



回答5:


It's a conditional assignment in Ruby. You can read more about it here: Ruby Operators




回答6:


It sets a value to the variable if the variable isn't already set. Meaning

class Something
  attr_accessor :some_value

def perform_action
  @some_value ||= "Mom"
  puts @some_value
end

foo = Something.new
foo.perform_action -> "Mom"
foo.some_value = "Dad"
foo.perform_action -> "Dad"


来源:https://stackoverflow.com/questions/7714803/what-does-do-in-ruby-1-9-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!