更改方法中传递的变量 [英] Change variable passed in a method

查看:70
本文介绍了更改方法中传递的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用方法更改变量的内容?也许我说的不正确.有什么方法可以像C中那样获得对变量的引用?示例:

How can I change the contents of a variable using a method? Maybe I'm not saying this correctly. What is a way to get the reference to a variable like in C? Example:

// main stuff
int gorilla = 29;
makeMeABanana(&gorilla);

void makeMeABanana(int *gorilla) { }

我该如何在Ruby中做类似的事情?

How can I do something like this in Ruby?

推荐答案

最近在ruby-talk邮件列表上,有人询问编写一个交换函数,其中swap(a,b)将交换变量"a"的值和"b".通常,这在Ruby中无法完成,因为交换函数将不会引用调用函数的绑定.

Recently on the ruby-talk mailing list, someone asked about writing a swap function where swap(a,b) would swap the values of the variables "a" and "b". Normally this cannot be done in Ruby because the swap function would have no reference to the binding of the calling function.

但是,如果我们显式传递绑定,则可以编写类似交换的函数.这是一个简单的尝试:

However, if we explictly pass in the binding, then it is possible to write a swap-like function. Here is a simple attempt:

 def swap(var_a, var_b, vars)
    old_a = eval var_a, vars
    old_b = eval var_b, vars
    eval "#{var_a} = #{old_b}", vars
    eval "#{var_b} = #{old_a}", vars
  end

  a = 22
  b = 33
  swap ("a", "b", binding)
  p a                          # => 33
  p b                          # => 22

这实际上有效!但这有一个很大的缺点.将"a"和"b"的旧值插入到字符串中.只要旧值是简单的文字(例如整数或字符串),则最后两个eval语句将看起来像:eval"a = 33",vars.但是,如果旧值是复杂对象,则eval看起来像就像eval"a =#",vars.糟糕,对于无法在往返字符串中返回的任何值,此操作都会失败.

This actually works! But it has one big drawback. The old values of "a" and "b" are interpolated into a string. As long as the old values are simple literals (e.g. integers or strings), then the last two eval statements will look like: eval "a = 33", vars". But if the old values are complex objects, then the eval would look like eval "a = #", vars. Oops, this will fail for any value that can not survive a round trip to a string and back.

引自: http://onestepback.org/index.cgi/Tech /Ruby/RubyBindings.rdoc

这篇关于更改方法中传递的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆