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

What does it do?

ruby -v = 1.9.2p290

jondavidjohn
  • 61,812
  • 21
  • 118
  • 158
ahmet
  • 4,955
  • 11
  • 39
  • 64
  • Duplicate: [What does `||=` mean in Ruby?](http://StackOverflow.Com/q/995593/), [What does `||=` mean in Ruby?](http://StackOverflow.Com/q/3800957/), [what is `||=` in ruby?](http://StackOverflow.Com/q/3945711/), [Double Pipe Symbols in Ruby Variable Assignment?](http://StackOverflow.Com/q/4500375/), [What does the “`||=`” operand stand for in ruby](http://StackOverflow.Com/q/5124930/), [what does a `||=` mean in Ruby language?](http://StackOverflow.Com/q/5230162/), [Is the ruby operator `||=` intelligent?](http://StackOverflow.Com/q/2989862/), … – Jörg W Mittag Oct 11 '11 at 01:46
  • … [What does `||=` mean?](http://StackOverflow.Com/q/7556902/), and probably many others as well. See also [The definitive list of `||=` (OR Equal) threads and pages](http://Ruby-Forum.Com/topic/151660/). *Please*, *please*, *please* don't ask duplicate questions. It just scatters information around the site that would much better be found in just one place. Thank you! – Jörg W Mittag Oct 11 '11 at 01:47
  • @JörgWMittag: Why tell a 393 rep user not to ask duplicate questions, rather than 4 people who have more than 3K rep (and therefore have close right privileges) not to answer duplicate questions? – Andrew Grimm Oct 11 '11 at 02:06

6 Answers6

5

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"
jondavidjohn
  • 61,812
  • 21
  • 118
  • 158
2

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

Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72
1

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.

eykanal
  • 26,437
  • 19
  • 82
  • 113
1

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.
d11wtq
  • 34,788
  • 19
  • 120
  • 195
1

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

Jakob W
  • 3,347
  • 19
  • 27
1

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"
Timbinous
  • 2,863
  • 1
  • 16
  • 9