Po pierwsze, nie można wdrożyć puti
i bezpośrednio wywołać puti a_var
, aby uzyskać dane wyjściowe jako a_var = value of a_var
. W ciele puti
Ruby widzi tylko formalne nazwy parametrów puti
, nie może wywnioskować rzeczywistych nazw parametrów.
W niektórych innych językach, takich jak C/C++, można użyć Macro, aby zaimplementować swoją puti
. To inna historia.
Można jednak wdrożyć put :a_var
, korzystając z pomocy Continuation. W innym pytaniu "Can you eval code in the context of a caller in Ruby?", Sony Santos wprowadził implementację caller_binding, aby uzyskać powiązanie wywołującego (coś podobnego do funkcji wywołującej perl).
Implementacja powinna zostać nieco zmieniona, ponieważ callcc
zwraca zwracaną wartość bloku przy pierwszym powrocie. Dostaniesz więc instancję Continuation
zamiast nil
. Oto zaktualizowana wersja:
require 'continuation' if RUBY_VERSION >= '1.9.0'
def caller_binding
cc = nil # must be present to work within lambda
count = 0 # counter of returns
set_trace_func lambda { |event, file, lineno, id, binding, klass|
# First return gets to the caller of this method
# (which already know its own binding).
# Second return gets to the caller of the caller.
# That's we want!
if count == 2
set_trace_func nil
# Will return the binding to the callcc below.
cc.call binding
elsif event == "return"
count += 1
end
}
# First time it'll set the cc and return nil to the caller.
# So it's important to the caller to return again
# if it gets nil, then we get the second return.
# Second time it'll return the binding.
return callcc { |cont| cc = cont; nil }
end
# Example of use:
def puti *vars
return unless bnd = caller_binding
vars.each do |s|
value = eval s.to_s, bnd
puts "#{s} = #{value.inspect}"
end
end
a = 1
b = 2
puti :a, :b
e = 1 # place holder...
# => a = 1
# b = 2
Zanotuj puti
nie powinno być ostatnim oświadczenie o swoim programie, inaczej interpreter Ruby natychmiast przerwać, a funkcja śledzenia nie ma szans, aby uruchomić. To jest punkt ostatniej linii "miejsce właściciela".
http://stackoverflow.com/questions/1356749 To jest bardziej zbliżone do Twoich wymagań. –