Hi, I’ve been going through the “The well grounded rubyist” recently but
got stuck when I came
across this particular code snippet.
My questions are in the #comments lines below as well.
A variable is getting assigned a value from a singleton method but not
being initialized as an object, so how can it access the attributes of
the ticket object
below??
Thank you very kindly, for your help
#!/usr/bin/ruby
class Ticket
attr_reader :venue, :date
attr_accessor :price
#This method wasn't in the code snippet of
#the book, I added it, but that's not the Question
def initialize(venue, date)
@venue=venue
@date=date
end
end
def Ticket.most_expensive(*tickets)
tickets.max_by(&:price)
end
Hi Jesus, Thanks for your answer and I’ve put it to the test below and
it works not only
in code but also in freaking me out.
Now I’m even more confused as I don’t know how your suggestion has the
same effect.
The code below does not show me how the variable highest is connected in
any way
to the class Ticket.
It has been assigned the return value of an array’s method! isn’t it?
So I just don’t see how it becomes a Ticket object ?
What am I missing to understand here ?
Thank you.
#!/usr/bin/ruby
class Ticket
attr_reader :venue, :date
attr_accessor :price
def initialize(venue, date)
@venue=venue
@date=date
end
The return value of:
highest = [th, cc, fg].max_by(&:price)
is an object - Either of th, cc, fg
Therefore the object can be referenced via it’s attributes. Great.
Also, highest = Ticket.most_expensive(th,cc,fg) will set
highest to refer to an object - Any one of the “tickets” args
(which are objects!) sent to the singleton method. Awesome.