25. class Cat
def meow; ’meow’; end
end
cat = Cat.new
new_cat = Cat.new
def cat.argh
'argh'
end
p cat.meow
=> "meow"
p cat.argh
=> "argh"
p new_cat.argh
NoMethodError: undefined method `argh' for
#<Cat:0x007fda63085878>
27. THE OBJECT MODEL
• Every object, classes included, has its
own “real class,” be it a regular class
or an eigenclass
• The superclass of the eigenclass is the
object class
• The superclass of the eigenclass of a
class is the eigenclass of the class’s
superclass
28. THE OBJECT MODEL
class C; end
class D < C; end
obj = D.new
#Object
C
#C
D
obj
Object
#D
#obj
Metaprogramming Ruby - Pag. 125
34. duck typing
When I see a bird that walks like a duck
and swims like a duck and quacks like a
duck, I call that bird a duck
http://en.wikipedia.org/wiki/Duck_typing
35. class Type1
def foo; "I'm type1"; end
end
!
class Type2
def foo; "I'm type2"; end
end
def get_class
rand < 0.5 ? Type1 : Type2
end
!t
= get_class.new
p t.foo
=> "I'm type2" #or I'm type1
38. METAPROGRAMMING
Metaprogramming is the writing of
computer programs that write or
manipulate other programs (or
themselves) as their data […]
http://en.wikipedia.org/wiki/Metaprogramming
40. class Settings
def initialize(options)
options.each do |key, value|
self.instance_variable_set "@#{key}", value
self.class.send :define_method, key,
proc{self.instance_variable_get("@#{key}")}
self.class.send :define_method, "#{key}=",
proc{|v| self.instance_variable_set("@#{key}", v)}
end
end
end
c = Settings.new YAML.load_file("config.yaml")
!
p c.title # => "metaprogramming ruby"
p c.author # => "Paolo Perrotta"
p c.pub_year # => "2010"
!
c.title = 'metaprogramming ruby 2.00’
p c.title # => "metaprogramming ruby 2.00”
41. HOOKS
Since all code is executed. You can
intercept some “facts” about it.
inherited, append_features, included,
extend_object, extended, initialize_copy,
const_missing
43. BUT THERE’S MORE
> [1, 2, 3] * 3 == [1, 2, 3, 1, 2, 3, 1, 2, 3]
> 1_000_000
> a = a || []
> a = [1,2,3]; a[-1]
> [1,2,3].shuffle
> (0..9).each { ... }
> 3.times {...}
> def name=(value); ...
44. PHILOSOPHY
I hope to see Ruby help
every programmer in the
world to be productive, and
to enjoy programming, and
to be happy. That is the
primary purpose of Ruby
language.
Yukihiro
Matsumoto
50. LINGUISTIC RELATIVITY
“The principle of linguistic relativity holds
that the structure of a language affects
the ways in which its respective speakers
conceptualize their world.”
Sapir–Whorf hypothesis
http://en.wikipedia.org/wiki/Linguistic_relativity
51. THE PRAGMATIC
PROGRAMMER
“Learn at least one new language every
year. Different languages solve the same
problems in different ways. By learning
several different approaches, you can
help broaden your thinking and avoid
getting stuck in a rut.”
The Pragmatic Programmer