以下代码将收集器变量“sql”作为字符串从生命开始,然后强制转换为fixnum。这种转变没有明显的理由。
segs=['segment1', 'segment2']
sx=1
sqlout = segs.inject("select ") do | sql, seg|
puts "class of sql: #{sql.class}"
salias = "#{seg.slice(1,3)}"
if sx > 1 then sql <<= " ," end # this if the offending line 8
sql <<= "#{salias}.score as #{seg}_score"
puts "class of sql at end: #{sql.class}"
sx+=1
end
结果
class of sql: String
class of sql at end: String
class of sql: Fixnum
TypeError: can't convert String into Integer
<< at org/jruby/RubyBignum.java:751
<< at org/jruby/RubyFixnum.java:1155
(root) at ./pivot.rb:8
each at org/jruby/RubyArray.java:1613
inject at org/jruby/RubyEnumerable.java:820
(root) at ./pivot.rb:5
答案 0 :(得分:2)
您在inject
中返回了错误的值。以下应该有效
segs=['segment1', 'segment2']
sx=1
sqlout = segs.inject("select ") do | sql, seg|
puts "class of sql: #{sql.class}"
salias = "#{seg.slice(1,3)}"
if sx > 1 then sql <<= " ," end # this if the offending line 8
sql <<= "#{salias}.score as #{seg}_score"
puts "class of sql at end: #{sql.class}"
sx+=1
sql
end
请记住inject
中的下一个输入是块的返回,而不是传递的第一个变量。
结果:
class of sql: String
class of sql at end: String
class of sql: String
class of sql at end: String