How can this be achieved in Ruby? Can it be done without repeating the variable? Javascript:
b = a || 7 This assigns a if a is not 0 and 7 otherwise
One specific case is converting date.wday to 7 if it returns 0 (Sunday).
Just out of curiosity:
class Object def javascript_or?(other) (is_a?(FalseClass) || nil? || '' == self || 0 == self) ? nil : self end end and:
a = b.javascript_or?(7) case self which might be faster than this chain of || operators.There are only two falsy values in Ruby: nil and false. So, if you really want this approach
a = b == 0 ? 7 : b is a plausible solution, because 0 can't be evaluated as false.
However, a better option for your need is cwday, and not wday. Then you don't need to make this comparison anymore, because it returns 1 for Monday, 2 for Tuesday, and finally 7 for Sunday, as you need.
date = Date.new(2016,19,6) # => Jun 19 2016, Sunday date.cwday # => 7 You can use ternary operator:
date.wday == 0 ? 7 : date.wday cwday, I think this is a close second. I have no idea why it was downvoted, unless it was by the OP, who found it insulting.What you're describing here is less of a logical problem and more of a mapping one:
WEEKDAY_MAP = Hash.new { |h,k| h[k] = k < 7 ? k : nil }.merge(0 => 7) This one re-writes 1..6 to be the same, but 0 becomes 7. All other values are nil.
Then you can use this to re-write your day indicies:
b = WEEKDAY_MAP[a] If at some point you want to tinker with the logic some more, that's also possible.
day || 7 ? :D|| 7 is never going to happen so you may as well abandon that idea: The When in Rome principle applies here. If you're doing a mapping operation, express it as such. In other languages you can take advantage of zero being a false value so the simplest expression of your desire does vary considerably depending on constraints.
[date.wday, 7].detect { i != 0 }cwday(instead ofwday) – it returns7(instead of0) if the date is a Sunday ;-)wdayor not?cwdaysolved my case.