简体   繁体   中英

Ruby to_ary method confusion

I looked up the to_ary method of the Array class. I am confused how the method relates to its source doc.

to_ary method => Returns self

If I do this:

1.9.3-p0 :013 > a = [1,33,42]
=> [1, 33, 42] 
1.9.3-p0 :014 > a.to_ary
=> [1, 33, 42] 
1.9.3-p0 :015 > a
=>[1, 33, 42] 

Why is the attribute static VALUE necessary? Is VALUE the retriever? Does a space (instead of a comma) between arguments mean the second argument is the method called by the receiver?

static VALUE

rb_ary_to_ary_m(VALUE ary) 
{
   return ary;
}

Best,

cj3kim

This is C code. The Ruby interpreter is wrote in the C language. In this code, the first argument is used as self . A equivalent in ruby would be:

def to_ary
  return self
end

What is happening here is, that it is treating it as an array and the IRB is using the print method to push it out to the screen. Print will convert the to_ary to a string, therefore you won't see any difference, you will see a difference when you use puts. Puts uses to_ary in the background whereas print uses to_s .

The to_ary method is for implicit conversions, while to_a is for explicit conversion. A good example is the method flatten , which takes an multidimensional array and flattens it into a singular dimensional array. Unless you use the dangerous method, the actual variable stays the same as before when you continue using out of concatenation of the flatten method. This is because flatten uses to_ary and not to_a , whereas flatten! uses to_a . to_ary treats it like an array for that instance, but does not permanently change the variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM