I have been learning ruby and interested in knowing how ‘each’ is implemented in the array class. I saw one documentation here and it looks like this is how ‘each’ is written;
# within class Array...
def each
for each element
yield(element)
end
end
I did exactly write the code above (without the comment#) in the ruby console (I’m using 1.9.2) and got this syntax error
:SyntaxError: (irb):2: syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '('
(irb):5: syntax error, unexpected keyword_end, expecting $end
Is this happening due to incomplete array class implementation (i.e ‘element’ is not defined or is this because of anything else? I’d also like to know how ‘each’ and other basic fnctions are implemented. Any reference to the right documentation/answers would be helpful. Let me know if this is a duplicate (i didnt see any similar questions). thanks
First off, the syntax of your
forstatement is off, it should be something likefor element in elements, which is almost equivalent toelements.each { |element| ... }except that it doesn’t introduce a new scope. In factforis implemented usingeach, as can be seen when you try to call it on a method that has no definedeachmethod:Regarding your syntax error: since you are reopening a class, when the Ruby parser sees the standalone
eachit usesselfas the receiver, so it translates your statement tofor self.each element, whereelementis thetIDENTIFIERmentioned, whereas something likeself.each do |element| ... endwould have been expected.As for the implementation of
Array#each, it’s implemented in C and looks like thisThis is basically what you tried to write in Ruby in C.