void foo(int &x) ->;红宝石?通过引用传递整数?
作为给我的 C++ 编程作业增添趣味的一种方式,我决定不再将书中的 C++ 输入到我的计算机上,而是用 Ruby 对其进行改造。是的,这有点傻,但我很无聊。
不管怎样,我在将这种函数转换为 Ruby 时遇到了麻烦。
void swap(int &a,int &b){
int c=b;
b=a;
a=c
}
函数内的等效 ruby 代码是什么??
as a way to spice up my C++ programming homework, I've decided to instead of typing the C++ from the book onto my computer, instead reforming it in Ruby. Yes it's a bit silly, but I'm bored.
Anyway, I'm having trouble converting this kind of function to Ruby
void swap(int &a,int &b){
int c=b;
b=a;
a=c
}
What would be the equivalent ruby code inside a function ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Ruby 是严格按值传递的。总是。但有时这些值是指针。
这里有几个链接:
请注意,虽然所有这些都说“Java”,但它们实际上应该说“Smalltalk 及其后代”,其中包括 Java、Ruby 和大量其他语言。
我认为大部分混乱源于两个问题:
顺便说一句:我故意将“指针”与面向对象的 OO 拼写错误,以表明我不是在谈论原始内存地址,我是在谈论原始内存地址。谈论对对象的不透明引用(出于明显的原因,我不想使用“引用”这个词;如果您知道一个既不是“指针”也不是“引用”的更好的词,我很乐意听到它)。
Ruby is strictly pass-by-value. Always. But sometimes those values are poointers.
Here's a couple of links:
Note that while all of these say "Java", they should really say "Smalltalk and its descendants", which includes Java, Ruby and a ton of other languages.
I think most of the confusion stems from two problems:
BTW: I deliberately misspelt "poointers" with an OO for object-orientation to make it clear that I am not talking about raw memory addresses, I am talking about opaque references to objects (and for obvious reasons I do not want to use the word "reference"; if you know a better word that is neither "pointer" nor "reference", I'd love to hear it).
在 Ruby 中,参数是按值传递的。因此,以下方法永远不会产生任何效果:
另一方面,大多数对象都是引用,例如字符串,因此您可以编写
这将交换两个参数的字符串值。
整数是立即数,因此没有等价于
replace
;你不能写swap_integers
。无论如何,在 Ruby 中,您可以通过编写
a, b = b, a
来进行交换In Ruby, arguments are passed by value. So the following method will never have any effect:
On the other hand, mosts objects are references, for examples strings, so you could write
This would swap the string values of the two arguments.
Integers are immediates, so there is no equivalent to
replace
; you can't writeswap_integers
.Anyways, in Ruby, you swap by writing
a, b = b, a