1

After importing data from an R plugin to my ruby script, I have an array that appears to act like a hash. Does anyone know what's going on here?

r_edges.class
#=> Array < Object

r_edges[0]
#=> returns data from index 0 as expected

r_edges['GO:0010035']
# r_edges['GO:0010035']['edges'] also works
#=> returns data at the index that is named 'GO:0010035', see the to_s output below    

r_edges
#=> [  0] [
[0] [
  [ 0] 2,
  [ 1] 3,
  [ 2] 4,
  [ 3] 5,
  [ 4] 6,
  [ 5] 7,
  [ 6] 8,
  [ 7] 9,
 ...... etc.

r_edges.to_s
#=> "[GO:0006260=[edges=[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 28, 29, 31, 32, 33, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, 46, 48, 51, 55, 56, 57, 58, 59, 60, 63, 67, 69, 71, 78, 81, 83, 84, 89, 90, 91, 92, 94, 95, 96, 97, 99, 100, 104, 108, 109, 112, 116, 117, 123, 124]], GO:0006271=[edges=[1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 28, 29, 36, 40, 46, 67]], GO:0022616=[edges=[1, 2, .... etc. 

I got the data by using the Ruby Rserve gem and interating with an R S4 object like so:

con = con=Rserve::Connection.new
r_edges = con.eval("SOME S4 OBJECT").to_ruby

It is actually helpful for me to get the 'named index' data when I'm looping through the array but I have no idea how to access that value.

3
  • Are you using any other libraries or anything? How are you importing the data? Also, what version of Ruby? Commented Apr 3, 2014 at 22:23
  • Ruby itself has hash support like {:a => 'a', :b => 'b'}. Commented Apr 3, 2014 at 22:26
  • @XiaogeSu, I am well aware. My question is why is my Array acting like a hash. Commented Apr 3, 2014 at 22:28

1 Answer 1

2

It's behaving funny because Ruby is awesome! It lets you shove functionality into an object without subclassing it.

From the Rserve gem's rlist class:

# Returns an Array with module WithNames included
# * Unnamed list: returns an Array
# * Named List: returns a Hash. Every element without explicit name receive
#   as key the number of element, 1-based
#
def to_ruby
  data=to_a
  data.extend WithNames
  data.names=@names
  data
end

Which shoves the WithNames module into the array, which has a couple methods for [] (look around line 121).

Sign up to request clarification or add additional context in comments.

1 Comment

ahhhh! I was searching for class Array in the repo to see if they were opening it up but didn't think about extending just the object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.