简体   繁体   中英

Why doesn't this comparison approach work in Ruby

Let's say I have array

s = ['Armando','P']
p s[1] ==  ('R' || 'P' || 'S')

I though that would return true since P is included in the "OR" comparison but it returns false

Because that's not how it works. The definition of A || B A || B is A if A is truthy, B otherwise. The evaluation order is as in mathematics, parentheses go first; so ('R' || 'P' || 'S') is 'R' (because at least the first of them is truthy; in fact all of them are). Then 'P' == 'R' is obviously false.

You need to write it as:

s[1] == 'R' || s[1] == 'P' || s[1] == 'S'

Shorter alternative:

%w(R P S).include?(s[1])

The problem lies in that the expression 'R' || 'P' || 'S' 'R' || 'P' || 'S' 'R' || 'P' || 'S' evaluates to 'R' (because it's the first truthy value in the expression. Obviously 'P' != 'R' , that is why the complete expression evaluates to false . What I would do is use a regular expression instead:

# Revised regexp according to Cary Swoveland's recommendation:
!!s[1][/\A[RPS]\z/]  #=> true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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