1

The following code has the collector variable "sql" starting off life as a string but then coerced into fixnum. There is no apparent reason for such a conversion.

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

The results are

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
4

1 回答 1

2

You are returning the wrong value in inject. The following should work

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

remember that the next input in inject is the return of the block, not the first variable passed.

results:

class of sql: String
class of sql at end: String
class of sql: String
class of sql at end: String
于 2013-05-03T21:38:43.717 回答