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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With