I’m new to both Ruby and closures, and I’m trying to nail down exactly
what’s going on in an example on p. 56 in the 2nd edition of
Programming Ruby:
songlist = SongList.new
class JukeboxButton < Button
def initialize(label, &action)
super(label)
@action = action
end
def button_pressed
@action.call(self)
end
end
start_button = JukeboxButton.new(“Start”) { songlist.start }
pause_button = JukeboxButton.new(“Pause”) {songlist.pause }
(I typed this in manually, so if there are typos, they come from me,
and not the book.)
I understand that @action is an instance variable that points to a
Proc object containing the block of code in the curly brackets. And I
think I understand the idea that the context of the block is saved
along with the code in the Proc object.
What I don’t understand is why we need the parameter “self” in:
@action.call(self)
When someone presses the start button, that generates a call to
start_button.button_pressed, right? So when we run that method, we do
@action.call, which would songlist.start to run.
Why do we need “self”? Doesn’t “self” refer to start_button, which is
an instance of JukeboxButton? Why would songlist need to know about
the button?
And if we were going to pass a parameter when we run @action.call,
wouldn’t the block of code need to have a parameter in it? Like this:
start_button = JukeboxButton.new(“Start”) { |x| songlist.start }
I realize that doesn’t make sense – the parameter isn’t used in that
code block. But I’m pretty confused by what’s going on here.
Thanks (and I hope this isn’t too dumb, or inappropriate.)