将字符串强制转换为Fixnum

时间:2012-11-19 02:48:17

标签: ruby

我正在看一些用Ruby 1.8编写的RubyQuiz代码,当我在1.9.2中运行它时,它现在抛出一个错误。这个方法

def encrypt(s)
  return process(s) {|c, key| 64 + mod(c + key - 128)}
end

给我以下错误

in `+': String can't be coerced into Fixnum (TypeError)

这是我的代码:

def mod(c)
  return c - 26 if c > 26
  return c + 26 if c < 1
  return c
end

def process(s, &combiner)
  s = sanitize(s)
  out = ""
  s.each_byte { |c|
    if c >= 'A'.ord and c <= 'Z'.ord
      key = @keystream.get
      res = combiner.call(c, key[0])
      out << res.chr
    else
      out << c.chr
    end
  }
  return out
end

1 个答案:

答案 0 :(得分:5)

您不能使用'+'运算符将String添加到Integer。在IRB,

 irb(main):001:0> 1 + '5'
 TypeError: String can't be coerced into Fixnum

或者相反:

irb(main):002:0> '5' + 1
TypeError: can't convert Fixnum into String

您必须先将字符串转换为FixNum,即

irb(main):003:0> '5'.to_i + 1
=> 6

irb(main):004:0> 1 + '5'.to_i
=> 6

“to_i”将接受字符串第一部分的整数部分并将其转换为FixNum:

irb(main):006:0> 1 + '5five'.to_i
=> 6

但是,当字符串没有数字时,您可能会得到意外的结果:

irb(main):005:0> 1 + 'five'.to_i
=> 1

在您的情况下,我认为您期望变量key的整数,但是正在获取字符串。您可能想要key.to_i。 希望这会有所帮助。

相关问题