Monthly Archives

December 2019

is_a? and respond_to? Ruby methods

By Posts No Comments

is_a? Method that tells you whether an object has a given class either as its class or as one of its class’s ancestral classes:

>> mag = Magazine.new
=> #<Magazine:0x36289c>
>> mag.is_a?(Magazine)
=> true
>> mag.is_a?(Publication)
=> true

respond_to? – the method that lets you determine in advance whether an object knows how to handle a particular method – can come in handy.

Method notation

By Posts No Comments

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