Frage

I'm working with the rserve-client gem, which allows a Ruby script to communicate with R via TCP/IP. Part of that involves serializing Ruby objects to send over the wire, and transparently converting the results that come back into Ruby.

However, the array objects returned have a strange notation associated with them I've never seen before, when an R table is translated back into Ruby.

For example an R table with a named id column and 3 values returns:

res
=> [|WN|"id"=[1,
   2,
   3]
res.to_s
=> "[id=[1, 2, 3]]"
res.class
=> Array
res.inspect
=> "#<Array:70227288405140 [id=[1, 2, 3]]>"
res.class.ancestors == Array.ancestors
=> true
=> [[1,
  2,
  3]]

Any idea what this is? Ideally I would like to convert it to a hash to use ID...to_hash doesn't get it. .to_a results in:

War es hilfreich?

Lösung

The answer is in the rserve gem source. Array has been decorated with a new pretty_print method:

def pretty_print(q)
  q.group(1,'[|WN|',']') {
  ...
end

https://github.com/clbustos/Rserve-Ruby-client/blob/a4edabd5c742f08a9b2394ce255707219aafd7df/lib/rserve/withnames.rb#L16

Andere Tipps

That is not a valid array notation. I don't have any specific knowledge of this gem, but I would guess the author took the frustrating path of lying to you. Here is a simple class that displays similar behavior.

class A < Array
  def class
    Array
  end

  def inspect
    "[|WN| blah=[1,2,3]]"
  end
end

Output

foo = A.new #=> [|WN| blah=[1,2,3]]
foo.class #=> Array
foo.class.ancestors == Array.ancestors #=> true

This practice is not as unusual as it should be. ActiveRecord::Relation at least used to do something similar.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top