Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby double pipe assignment with block/proc/lambda?

It is really nice to be able to write out

@foo ||= "bar_default"

or

@foo ||= myobject.bar(args)

but I have been looking to see if there is a way to write something like

@foo ||= do
  myobject.attr = new_val
  myobject.other_attr = other_new_val
  myobject.bar(args)
end

roughly equivilent in actually functional code to something like

@foo = if [email protected]?
         @foo
       else
         myobject.attr = new_val
         myobject.other_attr = other_new_val
         myobject.bar(args)
       end

And I suppose I could write my own global method like "getblock" to wrap and return the result of any general block, but I'm wondering if there is already a built-in way to do this.

like image 964
Misterparker Avatar asked Dec 30 '12 04:12

Misterparker


Video Answer


2 Answers

You can use begin..end:

@foo ||= begin
  # any statements here
end

or perhaps consider factoring the contents of the block into a separate method.

like image 105
jacknagel Avatar answered Sep 20 '22 06:09

jacknagel


I usually write it like this:

@foo ||= (
  myobject.attr = new_val
  myobject.other_attr = other_new_val
  myobject.bar(args)
)
like image 27
tothemario Avatar answered Sep 20 '22 06:09

tothemario