Skip to content

Instantly share code, notes, and snippets.

@marcomd
Created March 6, 2012 17:28
Show Gist options
  • Save marcomd/1987631 to your computer and use it in GitHub Desktop.
Save marcomd/1987631 to your computer and use it in GitHub Desktop.
Example 4
#yield
class A
def go(*attrs)
p "Before block"
attrs.each do |attr|
p yield(attr)
end if block_given?
p "After block"
end
end
a=A.new
a.go "1","2" do |i|
"ciao#{i}"
end
#&block
class B
def go(*attrs, &block)
p "Before block"
attrs.each do |attr|
p block.call(attr)
end if block_given?
p "After block"
end
end
b=B.new
b.go "1","2" do |i|
"ciao#{i}"
end
#alternativa con accesso diretto
class C
attr_reader :attr
def initialize
@attr = ""
end
def go(*attrs, &block)
p "Before block"
attrs.each do |attr|
@attr = attr
p instance_eval(&block)
end if block_given?
p "After block"
C.name
end
end
c=C.new
c.go "1","2" do
"ciao#{attr}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment