Procs and Blocks

If I alter the proc class, like so

class Proc
def keep(i)
@i = i
end

def whatIGot?()
  @i
end

end

and do something like so:

foo = Proc.new() {|*args|

}

foo.keep(624)

I run into issues when I do something like

def use(*args, &block)
block[*args]
$stdout.puts "Block kept: #{block.whatIGot} :
#{block.whatIGot.class}"
end

use (some, random, arguments, &foo)

here, whatIGot tends to be nil (which is fully understandable, since
we’re converting from some proc to a `block’ going to a method back to
a proc… but is there any sensable way to keep state?)

H,

···

In message “Procs and Blocks” on 04/03/13, matt mhm26@drexel.edu writes:

If I alter the proc class, like so

class Proc
def keep(i)
@i = i
end

def whatIGot?()
@i
end
end

Blocks (internal block data structure) and Procs (Ruby instance of the
class Proc) are converted back and forth during the execution, so that
there’s no guarantee that same Proc object is passed as a block
argument.

						matz.

“matt” mhm26@drexel.edu schrieb im Newsbeitrag
news:13383d7a.0403120756.4e28b88a@posting.google.com

If I alter the proc class, like so

class Proc
def keep(i)
@i = i
end

def whatIGot?()
  @i
end

end

and do something like so:

foo = Proc.new() {|*args|

}

foo.keep(624)

I run into issues when I do something like

def use(*args, &block)
block[*args]
$stdout.puts “Block kept: #{block.whatIGot} :
#{block.whatIGot.class}”
end

use (some, random, arguments, &foo)

here, whatIGot tends to be nil (which is fully understandable, since
we’re converting from some proc to a `block’ going to a method back to
a proc… but is there any sensable way to keep state?)

I don’t know why you want to do that since you can’t access instance
variables from inside the proc anyway (self does not point to the proc
instance). Typically the “interesting” things are stored in a procs
environment. You can even set and modify values there:

irb(main):078:0> x=66
=> 66
irb(main):079:0> p=proc {|a| a+x}
=> #Proc:0x10173a10@:79(irb)
irb(main):080:0> p.call 23
=> 89
irb(main):081:0> eval( “x”, p.binding )
=> 66
irb(main):082:0> x=10
=> 10
irb(main):083:0> p.call 23
=> 33
irb(main):084:0> eval( “x=20”, p.binding )
=> 20
irb(main):085:0> x
=> 20
irb(main):086:0> p.call 23
=> 43
irb(main):087:0> eval( “y=20”, p.binding )
=> 20
irb(main):088:0> eval( “y”, p.binding )
=> 20
irb(main):089:0> y
=> 20
irb(main):090:0>

If you need to carry along some state together with a proc, then you
probably should invent your own class and pass instances of that around.

class ProcWithInfo
attr :func
attr_accessor :name, :lengh; :size

def initialize(&b)
@func = b
end

def call(*args)
@func.call(*args)
end
end

etc.

Regards

robert