Câu hỏi phỏng vấn Ruby
Câu hỏi

Explain this ruby idiom: a ||= b

Câu trả lời

The Ruby idiom a ||= b is a common shorthand used in Ruby programming that serves as a conditional assignment operator. This idiom is used to assign the value of b to a if a is nil or false. Essentially, it is a concise way to write:

ruby Copy
a = a || b

This means that if a is either nil or false, then a will be set to b. If a already has a truthy value (anything other than nil or false in Ruby), a will retain its original value.

How It Works

The ||= operator first evaluates the left-hand side (a). If this evaluation yields nil or false (the only two "falsy" values in Ruby), Ruby then evaluates the right-hand side (b) and sets a to this value. If a is anything other than nil or false, a remains unchanged.

Practical Example

Consider a scenario where you might want to set a default value for a variable if it hasn't already been set:

ruby Copy
name ||= "Default Name"

Here, if name is nil or false, it will be set to "Default Name". If name already has a non-falsy value, it will remain as is.

Special Cases and Considerations

It's important to note that a ||= b is not exactly equivalent to a = a || b due to the way Ruby handles variable initialization and parsing. If a is not previously defined, a = a || b would raise an error because it tries to access an uninitialized variable a. However, a ||= b...

middle

middle

Gợi ý câu hỏi phỏng vấn

junior

What does it mean to coerce an object? Why would you do it?

junior

What are two uses of the splat operator?

senior

How exactly does it work?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào