2009-07-09 55 views
0

为什么心不是说工作:二进制或“|”在红宝石

>> s = "hi"                
=> "hi"                 
>> s == ("hi"|"ho")              
NoMethodError: undefined method `|' for "hi":String      
from (irb):2               
>> 

我不明白这一点..有没有这种语法的解决方案?由于

s == ("hi"|"ho") 
#is shorther than 
s == "hi" || s == "ho" 
+0

这个问题没有什么意义可言。字符串“hi”和“ho”的按位或等于“ho”,因此如果s ==“hi”,则您提出的表达式*将返回false *。如果使用不同的字符串,则按位或运算的结果可能更加荒谬。 – molf 2009-07-09 22:08:47

回答

9

是的,按位运算符|是不是在String类中定义:http://ruby-doc.org/core/classes/String.html

考虑这样的表现:

["hi", "ho"].include? myStr 

irb(main):001:0> s = "hi" 
=> "hi" 
irb(main):002:0> ["hi", "ho"] 
=> ["hi", "ho"] 
irb(main):003:0> ["hi", "ho"].include? s 
=> true 
irb(main):004:0> s = "foo" 
=> "foo" 
irb(main):005:0> ["hi", "ho"].include? s 
=> false 
5

在最高级语言的这种语法是行不通的,你必须坚持的时间越长语法:

小号==“喜” || s ==“ho”

注意|是一个按位或,而||是定期或

1

你可以把工作方式:

irb> class Pair 
     def initialize(strA,strB) 
     @strA,@strB = strA,strB 
     end 
     def ==(string) 
     string == @strA || string == @strB 
     end 
     def |(other) 
     Pair.new(self,other) 
     end 
    end 
#=> nil 
irb> class String 
     def |(other) 
     Pair.new(self,other) 
     end 
     alias old_equals :== 
     def ==(other) 
     if other.kind_of? Pair 
      other == self 
     else 
      old_equals other 
     end 
     end 
    end 
#=> nil 
irb> ("one"|"two") == "one" 
#=> true 
irb> ("one"|"two") == "two" 
#=> true 
irb> ("one"|"two") == "three" 
#=> false 
irb> "one" == ("one"|"two") 
#=> true 
irb> "three" == ("one"|"two"|"three") 
#=> true 

但由于这涉及到一个相当低级类的一些猴子补丁,我不会建议依赖于它。其他人会讨厌阅读你的代码。

+3

我是...我不会让你失望的,因为这对于这个问题来说确实是一个非常简洁的答案......但是如果你曾经靠近一个代码库,我坚持用这个代码库,我有一块半砖袜子上刻着你的名字。听起来不错? – 2009-07-09 16:11:04

+0

哦同意了。只是因为它可以做并不意味着它应该。 – rampion 2009-07-09 23:20:54

1

Ruby支持类型为Fixnum和Bignum的二进制'或'和other binary operations,表示任何整数。就我所知,字符串或任何其他类型都不支持按位操作。

正如其他人所提到的,您可能需要的不是二元操作。但是,你可以轻松地获得字符的整数表示,这样你就可以像这样比较字符:

a = "Cake" 
b = "Pie" 
puts a[0] | b[0] # Prints "83" - C is 67 and P is 80. 

您可以轻松地得到比较数组一些转换。

a = "Cake" 
b = "Pie " # Strings of uneven length is trivial but more cluttered. 

a_arr = a.split(//) 
b_arr = b.split(//) 
c_arr = [] 

a.each_with_index { |char, i| c.push(a[i].to_i | b[i].to_i) } 
# If you *really* want an ASCII string back... 
c = c_arr.collect(&:chr).join 
3

你可以使用阵列上的include?方法,如果你有几个==测试做:

["hi", "ho"].include?(s) 

对于两次检查,虽然不会缩短,但会缩短三次或更多次。

1

就我所知,此语法在任何语言中都不存在。

你说

s == ("hi"|"ho") 

什么字面翻译为“按位或字符串‘喜’和‘豪’起来,然后将它们与我们比较”。如果您不明白为什么这不是您要查找的内容,请尝试写下“hi”和“ho”的ASCII代码,然后逐位将它们组合在一起。你会得到完整的胡言乱语。

0

你可以使用正则表达式:

像这样:

regex = /hi|ho/ 
s = "hi" 
t = "foo" 

s =~ regex 
#=> 0 

t =~ regex 
#=> nil