to_chr
函数应该返回加密数组但转换为字符。我尝试了很多东西并评论了那些没有用的东西。
class Encrypt
def initialize(code, string)
@code = code
@string = string
@encrypted = []
end
def to_byte
@string.each_byte do |c|
@encrypted.push(c + @code)
end
print @encrypted
end
def to_chr
n = @encrypted.length
# n.times do |i|
# @encrypted.push(i.chr)
# end
print @encrypted[0].chr
# @encrypted.each do |x|
# @encrypted.push(x.chr)
# end
# print @encrypted
end
end
goop = Encrypt.new(2, "hello")
goop.to_chr
#=> in `to_chr': undefined method `chr' for nil:NilClass (NoMethodError)
答案 0 :(得分:0)
def to_chr
@encrypted.each do |i|
print i.chr
end
print "\n"
end
请务必在to_byte
to_chr
goop = Encrypt.new(2, "hello")
goop.to_byte
goop.to_chr
返回:
jgnnq
答案 1 :(得分:0)
您创建了Encrypted
方法的实例,但您设置了@code = 2
,@string = "Hello"
和@encrypted = []
。因此,如果您致电@encrypted[0]
,红宝石会返回nil
。
所以你可以像这样修改你的课程:
class Encrypt
def initialize(code, string)
@code, @string, @encrypted = code, string, []
end
def to_byte
@string.each_byte { |c| @encrypted << c + @code }
end
def to_chr
to_byte if @encrypted.empty?
@encrypted.map(&:chr)
end
end
goop = Encrypt.new(2, "hello")
p goop.to_chr
# => ["j", "g", "n", "n", "q"]
我希望这会有所帮助