I tested this on console:
[] || 1 # => []
Shouldn't it return the value that exits, and not []
? I can change it to ternary operator, which works fine, but why does the condition above not work?
Because []
is truthy value in Ruby, so the second part of your expression is never executed, it always evaluates to []
. In Ruby, just false
and nil
aren't truthy.
Oh, anyway, you don't need that. map
returns an empty array if the array is empty.
Model.new(
name: abc.name,
description: abc.description,
product_ids: abc.product_ids.map(&:id)
)
The exact semantics of ||
are:
nil
or false
, return it nil
or false
, return the second expression So since []
is truthy it will evaluate to []
, as explained by @Ursus.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.