简体   繁体   English

Ruby相当于JavaScript运算符`||`

[英]Ruby equivalent to JavaScript operator `||`

How can this be achieved in Ruby? 如何在Ruby中实现这一目标? Can it be done without repeating the variable? 可以在不重复变量的情况下完成吗? Javascript: 使用Javascript:

b = a || 7

This assigns a if a is not 0 and 7 otherwise 这将指定a a不为0 ,否则为7

One specific case is converting date.wday to 7 if it returns 0 (Sunday). 一个特定情况是将date.wday转换为7(如果它返回0(星期日))。

There are only two falsy values in Ruby: nil and false . Ruby中只有两个假值: nilfalse So, if you really want this approach 所以,如果你真的想要这种方法

a = b == 0 ? 7 : b

is a plausible solution, because 0 can't be evaluated as false . 是一个合理的解决方案,因为0不能被评估为false

However, a better option for your need is cwday , and not wday . 但是,更好的选择是cwday ,而不是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. 然后你不再需要进行这种比较,因为它根据需要返回1表示星期一, 2表示星期二,最后7表示星期日。

date = Date.new(2016,19,6) # => Jun 19 2016, Sunday
date.cwday # => 7

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)

For the particular case of 0 and 7 : 对于07的特定情况:

a = (b + 6) % 7 + 1

:) :)

您可以使用三元运算符:

 date.wday == 0 ? 7 : date.wday

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 . 这个重写1..6是相同的,但0变为7.所有其他值都是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. 如果在某些时候你想要更多地修补逻辑,那也是可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM