我有以下方法:
def add(a,b)
a + " + " + b + " = " + (a + b)
end
以下RSpec测试正在进行中:
describe "add" do
it "returns a string with 1 and 2 added" do
expect( add(1,2) ).to eq("1 + 2 = 3")
end
it "returns a string with 5 and 7 added" do
expect( add(5,7) ).to eq("5 + 7 = 12")
end
end
我收到以下错误:
无法将字符串强制转换为Fixnum exercise.rb:2:in“+”
exercise.rb:2:在“添加”
exercise_spec.rb:5:在'
中的块(2级)中
我在没有通过考试的情况下尝试了以下内容:
"#{a}" + " + " + "#{b}" + " = " + (a + b)
答案 0 :(得分:1)
您可以将a
,b
,a + b
全部放入字符串插值中:
def add(a,b)
"#{a} + #{b} = #{a + b}"
end
add(1, 2)
# => "1 + 2 = 3"
抛出错误是因为代码试图连接字符串和数字:
>> " " + 2
TypeError: no implicit conversion of Fixnum into String
from (irb):1:in `+'
from (irb):1
from C:/Ruby21-x64/bin/irb:11:in `<main>'
如果你想这样做,你需要在连接之前将数字转换为字符串:
>> " " + (2).to_s
=> " 2"