Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a variable by returning a value from a block when assignment is nil

Tags:

ruby

I'm trying to set a variable to a value but the value might be nil. I need to do some processing if it is. Here's some example code:

car = cached_car || do
  new_car = Car.new 
  # do stuff to the object here
  send_car_to_cache(new_car)
  new_car
end

Unfortunately it's telling me that there is an unexpected do block. What am I doing wrong here?

Edit: the context may have been confusing, so here is the real world scenario where I am using it.

def tableView(table_view, cellForRowAtIndexPath:index_path)
  cell = table_view.dequeueReusableCellWithIdentifier(CELL_ID) || begin
    PostTableViewCell.alloc.initWithStyle(
      UITableViewCellStyleDefault, reuseIdentifier: CELL_ID
    )
  end

  configure_cell(cell, index_path)
  cell
end
like image 951
dimiguel Avatar asked Dec 03 '25 18:12

dimiguel


2 Answers

Welp, I figured it out. I didn't want to use do, the right keyword is begin.

car = cached_car || begin
  new_car = Car.new 
  # do stuff to the object here
  send_car_to_cache(new_car)
  new_car
end

Now if cached_car is null I can construct an object and return it.

like image 175
dimiguel Avatar answered Dec 06 '25 09:12

dimiguel


I would do something like this:

car = cached_car
unless car
  car = Car.new
  # do stuff to the object here
  send_car_to_cache(car)
end

It might make sense to extract that into a method:

def new_car
  Car.new.tap do |new_car|
    # do stuff to the object here
    send_car_to_cache(new_car)
  end
end

What could be used like this:

car = cached_car || new_car
like image 27
spickermann Avatar answered Dec 06 '25 09:12

spickermann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!