This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# class.instance_methods(false) | |
class Rubyist | |
# the code in the following method definition is executed later, | |
# when you eventually call the method | |
def what_does_he_do | |
@person = 'A Rubyist' | |
'Ruby programming' | |
end | |
end | |
an_object = Rubyist.new | |
puts an_object.class # => Rubyist | |
puts an_object.class.instance_methods(false) # => what_does_he_do | |
an_object.what_does_he_do | |
puts an_object.instance_variables # => @person | |
#respond_to | |
obj = Object.new | |
if obj.respond_to?(:program) | |
obj.program | |
else | |
puts "Sorry, the object doesn't understand the 'program' message." | |
end | |
#send | |
class Rubyist | |
def welcome(*args) | |
"Welcome " + args.join(' ') | |
end | |
end | |
obj = Rubyist.new | |
puts(obj.send(:welcome, "famous", "Rubyists")) # => Welcome famous Rubyists | |
#:method_missing | |
class Rubyist | |
def method_missing(m, *args, &block) | |
str = "Called #{m} with #{args.inspect}" | |
if block_given? | |
puts str + " and also a block: #{block}" | |
else | |
puts str | |
end | |
end | |
end | |
# => Called anything with [] | |
Rubyist.new.anything | |
# => Called anything with [3, 4] and also a block: #<Proc:0xa63878@tmp.rb:12> | |
Rubyist.new.anything(3, 4) { something } | |
#http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_2.html | |