Last active
August 29, 2015 14:18
-
-
Save mwlang/796ed6076c692504a33d to your computer and use it in GitHub Desktop.
Three new tricks in my Ruby bag: 1) pass in a method and save it for a later call 2) pass in a method and replace a current method's implementation 3) How to implement optional arguments
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 Foo | |
def hello | |
puts "gonna say hello" | |
"Hello #{world}" | |
end | |
def world | |
"World" | |
end | |
attr_reader :say_it | |
def initialize options = {} | |
@say_it = options[:another_way] || method(:hello) | |
define_singleton_method(:world, options[:another_world]) if options[:another_world] | |
end | |
def speak | |
instance_exec &say_it | |
end | |
end | |
begin | |
foobar = Foo.new | |
puts "lazy?" | |
puts foobar.speak | |
rescue Exception => e | |
puts "#{e.class.to_s}: #{e.message}" | |
end | |
begin | |
foobaz = Foo.new(another_way: lambda { "#{hello}, Sir!" }) | |
puts "lazy?" | |
puts foobaz.speak | |
rescue Exception => e | |
puts "#{e.class.to_s}: #{e.message}" | |
end | |
begin | |
foobaz = Foo.new(another_world: lambda { "Earth" }) | |
puts "lazy?" | |
puts foobaz.speak | |
rescue Exception => e | |
puts "#{e.class.to_s}: #{e.message}" | |
end | |
class Bar | |
def self.register(name = nil, options = {}) | |
if name.nil? | |
name = "foobaz" | |
elsif name.is_a?(Hash) && options == {} | |
name, options = "foobar", name | |
end | |
puts [name, options].inspect | |
end | |
end | |
Bar.register :something, :foo => 1, :bar => 2 | |
Bar.register \ | |
foo: 2, | |
bar: -> { puts "yeah" }, | |
baz: 3 | |
Bar.register |
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
>> ruby foo.rb | |
lazy? | |
gonna say hello | |
Hello World | |
lazy? | |
gonna say hello | |
Hello World, Sir! | |
lazy? | |
gonna say hello | |
Hello Earth | |
[:something, {:foo=>1, :bar=>2}] | |
["foobar", {:foo=>2, :bar=>#<Proc:0x007ffa88a50d18@foo.rb:61 (lambda)>, :baz=>3}] | |
["foobaz", {}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment