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:

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:

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

expert

What is the differnece between extend and include in ruby?

senior

What is the difference between Object#dup and #clone ?

middle

What is the main difference between procs and lambdas?

Bình luận

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

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