Ruby 不识别“^=”操作员
我有 ruby 1.9.2dev (2010-07-02) [i486-linux]。
我知道 ^=
是一个 ixor 运算符,如官方文档所示。
这是我从 shell 运行脚本时的输出。
root@desk:~/Desktop/cha03# ./cha03
./cha03:35:in `block in <main>': undefined method `^' for "\x1C":String (NoMethodError)
from ./cha03:35:in `each_byte'
from ./cha03:35:in `each_with_index'
from ./cha03:35:in `<main>'
这是产生错误的行:
key.each_byte.each_with_index { |b,i| key[i] ^= subkey[i % 4] }
I have ruby 1.9.2dev (2010-07-02) [i486-linux].
I know that the ^=
is a ixor operator as shown in the official documentation.
This is the output when I run the script from the shell.
root@desk:~/Desktop/cha03# ./cha03
./cha03:35:in `block in <main>': undefined method `^' for "\x1C":String (NoMethodError)
from ./cha03:35:in `each_byte'
from ./cha03:35:in `each_with_index'
from ./cha03:35:in `<main>'
And this is the line that makes the error:
key.each_byte.each_with_index { |b,i| key[i] ^= subkey[i % 4] }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 ruby 1.9
string[some_index]
不再是字节值,它将是一个字符串String 没有 ^ 方法,所以你会得到你所描述的错误。在 ruby 1.8.7 中,您将获得字节的值,并且一切都会起作用。我认为使用 unpack 将字符串转换为字节数组,对其进行操作然后将其全部放回一起会更幸运,类似于
In ruby 1.9
string[some_index]
is no longer the byte value, it will instead be a stringString doesnt have a ^ method, so you get the error you've described. In ruby 1.8.7 you would have got the byte's value instead and it would all have worked. I think you'll have better luck using unpack to turn the string into an array of bytes, manipulate that then put it all back together, something along the lines of
扩展类
String
以便能够轻松地与另一个字符串或数字进行异或
运算使用示例:
extending class
String
to be able to easyxor
-ed with another string or numberexample use: