Trying to alias for/foreach

L

Leslie Viljoen

Hello

I am new to Ruby, but enjoying it incredibly. I'd like to ask some advice:
I noticed that IO has a "foreach" iterator while Array's, etc. mostly call
their per-item iterators "each". I thought I could get rid of this
inconsistency
like this:

class MyIO<IO

alias :each :foreach
#error:
#: undefined method `foreach' for class `MyIO' (NameError)

end

Why doesn't it work?

Les

--
ruby -W2 -e "puts 'Just another good programmer'"

Leslie Viljoen [[email protected]]
Camary Consulting [http://www.camary.co.za]
Cellphone [083-6186100]
Personal web [http://mobeus.homelinux.org]
 
A

Alex Fenton

class MyIO<IO

alias :each :foreach
#error:
#: undefined method `foreach' for class `MyIO' (NameError)

end

IO.foreach is a _class_ method, not an instance method. It's a shortcut,
called like this:

IO.foreach(portname) { ... }

vs the instance method - which already exists - which is used like this:

IO.new(int, modestring).each { ... }

Given that an instance method already exists called 'each', you probably
don't want to create a class method with the same name - it's confusing.
But if you did

class MyIO < IO
class << self
alias :each :foreach
end
end

alex
 
D

David A. Black

Hi --

Hello

I am new to Ruby, but enjoying it incredibly. I'd like to ask some advice:
I noticed that IO has a "foreach" iterator while Array's, etc. mostly call
their per-item iterators "each". I thought I could get rid of this
inconsistency like this:

There's no inconsistency. "each" is a message you send to objects
that have a collection or series of elements to iterate through. An
Array instance is such an object. But IO is a Class object, and has
nothing that "each" would make sense for. An IO.each class method
would thus be out of sync and inconsistent with how "each" is used
elsewhere in Ruby.


David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

getuid 1
Array redefinition problem 12

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,234
Latest member
SkyeWeems

Latest Threads

Top