我正在尝试将变量设置为值,但值可能是nil.如果是的话,我需要做一些处理.这是一些示例代码:
car = cached_car || do
new_car = Car.new
# do stuff to the object here
send_car_to_cache(new_car)
new_car
end
Run Code Online (Sandbox Code Playgroud)
不幸的是,它告诉我有一个意外的do阻止.我在这做错了什么?
编辑:上下文可能令人困惑,所以这是我正在使用它的真实场景.
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
Run Code Online (Sandbox Code Playgroud)
韦尔普,我明白了.我不想使用do,正确的关键字是begin.
car = cached_car || begin
new_car = Car.new
# do stuff to the object here
send_car_to_cache(new_car)
new_car
end
Run Code Online (Sandbox Code Playgroud)
现在,如果cached_car为null,我可以构造一个对象并返回它.