I read "An instance of a class can be extended to be subtly different, without needing to subclass" to mean simply
o = Foo() o.nonstandardattribute = bar
Yes, I think that's mostly what he means. Also, you can add and override methods in the same way. You can change the class directly -- monkey patching -- or you can create an instance and assign a function to an instance variable to override the method that the class contains. Other uses of first-class functions can accomplish all sorts of things; though honestly how they do that in Ruby (generally) I'm not sure, since it doesn't have "functions" per se, just methods. I get the impression there's some confusion there, with a couple techniques available.
they just write:def an_instance.amethod(args) ... end
It is a nice way to write stuff since it also allows for clear specification of class/module methods:class Foo # we are in Foo's scope, "self" is Foo def foo() puts "I'm an instance method" end def self.foo() puts "I'm a singleton method of a Class instance" end def self.bar() puts "In java parlance, I'm a static method of class Foo" end end
(Formatting fixed; I'm not actually the author of this comment)# Ian Bicking
There's also this:module Mod def hello "Hello from Mod.\n" end end class Klass def hello "Hello from Klass.\n" end end k = Klass.new k.hello -> "Hello from Klass.\n" k.extend(Mod) -> #<Klass:0x4018d554> k.hello -> "Hello from Mod.\n"
"o = Foo(); o.nonstandardattribute = bar"
this can't be done.
attributes in ruby are set via setter methodsclass Foo def std_attr= v @std_attr = v end end
although the simpler way to do it isclass Foo attr_writer :std_attr end
what "An instance of a class can be extended to be subtly different, without needing to subclass" actually means iss = 'a string' class << s def consonants gsub /[aeiou]/i, '' end end
s.consonants will give you " strng", but on any other string, it'll raise an undefined method error.