require 'erb'
def madlib(str, &block)
madlibber = Class.new do
attr_reader :vars, :story
def initialize(story)
@vars = {}
@story = story
end
%w{name animal verb adjective thing name2 name3}.each do |var|
class_eval <<-EOR
def #{var}(val)
vars[:#{var}] = val
end
EOR
end
def to_s
vars.each_pair do |name, value|
instance_variable_set("@#{name}".to_sym, value)
end
ERB.new(story).result(binding)
end
end
m = madlibber.new(str)
m.instance_eval(&block)
m.to_s
end
story = < said: "Now you just fought one hell of a <%= @animal %>
And I know you hate me, and you got the right
To <%= @verb %> me now, and I wouldn't blame you if you do.
But ya ought to thank me, before I die,
For the gravel in ya guts and the spit in ya eye
Cause I'm the <%= @adjective %> that named you "Sue.'"
I got all choked up and I threw down my <%= @thing %>
And I called him my pa, and he called me his son,
And I came away with a different point of view.
And I think about him, now and then,
Every time I try and every time I win,
And if I ever have a son, I think I'm gonna name him
<%= @name2 %> or <%= @name3 %>! Anything but Sue! I still hate that name!
EOS
str = madlib(story) do
name 'Alistair'
animal 'duck'
verb 'tickle'
adjective 'fellow'
thing 'spatula'
name2 'Horace'
name3 'Cynthia'
end
puts str