2009-07-09 57 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