Created
March 6, 2012 17:28
-
-
Save marcomd/1987631 to your computer and use it in GitHub Desktop.
Example 4
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
#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