Ruby inheritance is pretty cool, and in today’s tip we look at how subclassing a Struct object and using the Struct block will return the same # A normal struct object doesnt have a very pretty output Park = Struct.new(:location, :capacity) cp = Park.new("Central Park", "1,200,000") puts cp #=> #<struct Park location="Central Park", capacity="1,200,000">   # By creating a method on the Boardwalk class # we can make this much prettier Boardwalk = Struct.new(:location, :capacity) class Boardwalk def to_s "#{self.location} can hold #{self.capacity} people." end end vb = Boardwalk.new("Venice Beach", "200,000") puts vb #=> Venice Beach can hold 200,000 people.   # We can inherit the Struct and reduce our code class Mall < Struct.new(:location, :capacity) def to_s "#{self.location} can[…]

Clone() and dub() methods in the context of singleton methods can help us understand the state of an object. beer = "pilsner"   def beer.style puts ‘lager’ end   beer.style #=> lager   another_beer = beer.clone another_beer.style #=> lager   yet_another_beer = beer.dup yet_another_beer.style #=> clone.rb:17: undefined method `style’ for "pilsner":String (NoMethodError) Clone() includes the singleton methods of an object, as dup() does not. When you need the state of your object clone() is a beter choice. If I have an object I can’t change, maybe it’s a user or financial transaction, but I still need to have all of the state then clone() would be the right method to use. This way I can copy most of the information[…]

In Ruby, classes are objects. Classes can be created without a name. In most cases classes are named in the class definition, but it is possible to create anonymous classes and name them later. Let’s look at some examples. >> klass = Class.new => #<Class:0x007fe55713aa08>   >> klass.name => nil   >> BrettU = klass => BrettU   >> BrettU => BrettU   >> klass.name => "BrettU"   >> klass.class => Class Because classes are objects we are really creating objects and their name only is present because it is assigned to a constant. Classes are no different than other objects. Class methods are only singleton methods for a single instance of an object. # object with a class method[…]