Today I've seen |= for the first time and I'm trying to understand how it works and when it can be useful.
Some experiments show:
var |= nil
# => false
var |= false
# => false
var |= true
# => true
var |= 1
# => true
var |= nil
# => true
var |= false
# => true
var
# => true
Found in Github's html-pipeline gem.
def link_to_mentioned_user(login)
result[:mentioned_usernames] |= [login]
url = File.join(base_url, login)
"<a href='#{url}' class='user-mention'>" +
"@#{login}" +
"</a>"
end
I'm assuming that |= works like a guarded assignment with ||=, but casts the return value of the expession to be assigned to a boolean.
This means as long as var is falsy or undefined, the expression gets evaluated and the return value cast to a boolean gets assigned. As soon as var |= some_truthy_expression is called, var will be true and further calls to var |= expression_will_not_be_called will not evaluate the expression.
- Does it work like that, where can one find
|=in the Ruby docs? - When can
|=come in handy?