Ruby 中的“按引用传递参数"? [英] 'pass parameter by reference' in Ruby?

查看:51
本文介绍了Ruby 中的“按引用传递参数"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中,是否可以通过引用传递具有值类型语义的参数(例如 Fixnum)?我正在寻找类似于 C# 的ref"关键字的东西.

In Ruby, is it possible to pass by reference a parameter with value-type semantics (e.g. a Fixnum)? I'm looking for something similar to C#'s 'ref' keyword.

示例:

def func(x) 
    x += 1
end

a = 5
func(a)  #this should be something like func(ref a)
puts a   #should read '6'

顺便说一句.我知道我可以使用:

Btw. I know I could just use:

a = func(a)

推荐答案

您可以通过显式传入当前绑定来完成此操作:

You can accomplish this by explicitly passing in the current binding:

def func(x, bdg)
  eval "#{x} += 1", bdg
end

a = 5
func(:a, binding)
puts a # => 6

这篇关于Ruby 中的“按引用传递参数"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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