I have a piece of code in Ruby which goes as follows:
def check
if a == b || c == b
# execute some code
# b = the same variable
end
end
can this be written like
def check
if a || c == b
# this doesn't do the trick
end
if (a || c) == b
# this also doesn't do the magic as I thought it would
end
end
Or in a manner where I don't need to type b
twice. This is out of laziness and I would like to know.
The == operator, also known as equality or double equal, will return true if both objects are equal and false if they are not. str1 = “This is string”
The use of :: on the class name means that it is an absolute, top-level class; it will use the top-level class even if there is also a TwelveDaysSong class defined in whatever the current module is.
if [a, c].include? b
# code
end
This is, however, significantly slower than the code you want to avoid -- at least as long as a
, b
and c
are basic data. My measurements showed a factor of 3. This is probably due to the additional Array
object creation. So you might have to weigh DRY against performance here. Normally it should not matter, though, because both variants do not take long.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With