红宝石和参考文献。使用fixnums
我对 ruby 处理对象和引用的方式有所了解。替换的东西,等等......
我知道它不能在fixnum上工作,因为var是fixnum。但我希望更改函数内的 fixnum 的值,并且该值在外部变量中更改。
我该怎么做?
我想我可以使用像“1”这样的字符串,但这很脏。
I know a bit about ruby way to handle objects and references. The replace stuff, ect ...
I know it d'ont work on fixnum, cause the var is the fixnum. But i wish to change the value of a fixnum inside a function, and that the value changed in the ouside var.
How can i do this ?
I guess i can use a string like this "1" but that's quite dirty.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Ruby 将始终按引用传递(因为一切都是对象),但 Fixnum 缺少任何允许您更改值的方法。请参阅“void foo(int &x) -> Ruby? 传递通过引用整数?”了解更多详细信息。
您可以返回一个值,然后分配给您的变量,如下所示:
或者您可以将您的值包装在一个对象(例如哈希)中,并以这种方式更新它。
希望这有帮助。
Ruby will always pass-by-reference (because everything is an object) but Fixnum lacks any methods that allow you to mutate the value. See "void foo(int &x) -> Ruby? Passing integers by reference?" for more details.
You can either return a value that you then assign to your variable, like so:
or you could wrap your value in an object such as a Hash and have it updated that way.
Hope this helps.
您可以传递包含单个数字的数组,例如
[1]
,或传递一个哈希,例如{value: 1}
。不像字符串那么难看,因为你的数字本身仍然是一个数字,但比新类的开销更少......You could pass an array with a single number, like
[1]
, or a hash like{value: 1}
. Less ugly than a string, as your number itself remains a number, but less overhead than a new class...当我制作游戏时,我遇到了与您相同的问题。有一个数字分数代表你杀死了多少僵尸,我需要手动使其在玩家(增加分数)、分数栏和分数屏幕(显示分数)之间保持同步。我找到的解决方案是为分数创建一个单独的类,该类将包装该值并改变它:
When I was building a game I had the same problem you have. There was a numeric score that represented how many zombies you've killed and I needed to manually keep it in sync between Player (that incremented the score), ScoreBar and ScoreScreen (that displayed the score). The solution I've found was creating a separate class for the score that will wrap the value and mutate it: