Method notation

By 12/02/2019 Posts

Examples of this notation and what they refer to:

  • Ticket#price refers to the instance method price in the class Ticket.
  • Ticket.most_expensive refers to the class method most_expensive in the class Ticket. This notation is used when calling the most_expensive
    method.
  • Ticket::most_expensive also refers to the class method most_expensive in
    the class Ticket.

class Ticket
  def initialize(venue, date)
    @venue = venue
    @date = date
  end

  attr_reader :venue, :date
  attr_accessor :price
end

# *tickets Means any number argument
# The syntax &: is an abbreviated way of iterating over each of the elements in the tickets array and selecting the largest number. &: is often used with the map method, iterating over each element in an array, hash, or range and applying a method:
def Ticket.most_expensive(*tickets)
  p tickets.class
  tickets.max_by(&:price)
end

th = Ticket.new("Town Hall","2013-11-12")
cc = Ticket.new("Convention Center","2014-12-13")
fg = Ticket.new("Fairgrounds", "2015-10-11")
th.price = 12.55
cc.price = 10.00
fg.price = 18.00
highest = Ticket.most_expensive(th,cc,fg)
puts "The highest-priced ticket is the one for #{highest.venue}."

puts "Testing the response of a ticket instance...."
wrong = fg.most_expensive
codeByPasha

Author codeByPasha

More posts by codeByPasha

Leave a Reply