更改方法中传递的变量
如何使用方法更改变量的内容?也许我说得不正确。有什么方法可以像 C 中那样获取对变量的引用?示例:
// main stuff
int gorilla = 29;
makeMeABanana(&gorilla);
void makeMeABanana(int *gorilla) { }
我怎样才能在 Ruby 中做这样的事情?
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) { }
How can I do something like this in Ruby?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不应该这样做 - 您只是将完全适合 C 的技术移植到 Ruby,而它们在 Ruby 中不再适用。有几种奇特的方法可以解决这个问题(例如,使用在调用名称空间上关闭的 Proc 或 eval),但它们在 Ruby 中通常不合适,除非您确切地知道自己在做什么。
You should not do this - you're just porting techniques that are fully appropriate to C to Ruby, where they are no longer appropriate. There are several fancy ways around this (eg using a Proc closed over your calling namespace, or eval) but they are usually inappropriate in Ruby unless you know precisely what you're doing.
最近,在 ruby-talk 邮件列表上,有人询问编写一个交换函数,其中 swap(a,b) 将交换变量“a”和“b”的值。通常这不能在 Ruby 中完成,因为交换函数不会引用调用函数的绑定。
但是,如果我们显式传递绑定,则可以编写类似交换的函数。这是一个简单的尝试:
这确实有效!但它有一个很大的缺点。 “a”和“b”的旧值被插入到字符串中。只要旧值是简单的文字(例如整数或字符串),那么最后两个 eval 语句将如下所示: eval "a = 33", vars"。但是如果旧值是复杂对象,则 eval 将如下所示 之间往返的值都会失败。
就像 eval "a = #",哎呀,对于任何无法在字符串 /Tech/Ruby/RubyBindings.rdoc" rel="nofollow">http://onestepback.org/index.cgi/Tech/Ruby/RubyBindings.rdoc
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:
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.
Referred from : http://onestepback.org/index.cgi/Tech/Ruby/RubyBindings.rdoc
整数是对象,有一个 id,就像 Ruby 中的其他东西一样。它们的实现方式如下:
所有其他对象都有偶数 object_id 编号。无法将 7 (object_id 15) 更改为其他内容。
Integers are objects, with an id, like everything else in Ruby. They are implemented like this:
All other objects have even object_id numbers. There is no way to change 7 (object_id 15) into something else.