简体   繁体   English

Ruby支持像PHP这样的var引用吗?

[英]Does Ruby support var references like PHP?

In PHP, you can make two variables point to the same data. 在PHP中,您可以使两个变量指向相同的数据。

$a = 'foo';
$b = 'bar';
$a =& $b;
echo $a // Outputs: bar
echo $b // Outputs: bar

What we are trying to do in Ruby is set @app_session to be equal to session[@current_app[:uid]] . 我们在Ruby中尝试做的是将@app_session设置为等于session[@current_app[:uid]] So we only have to deal with @app_session in our app, and everything is automatically saved to the session. 所以我们只需要在我们的应用程序中处理@app_session ,一切都会自动保存到会话中。

Is there a way to do this in Ruby? 有没有办法在Ruby中做到这一点? After 15 minutes of reading, googling, and asking around here at the office, we're still lost... lol 经过15分钟的阅读,谷歌搜索,并在办公室询问,我们仍然失去了......哈哈

All variables in Ruby are references to an object. Ruby中的所有变量都是对象的引用。

a = b

means that a and b point to the same object. 表示a和b指向同一个对象。 That's why when you want to copy a given object, you need to write 这就是为什么当你想复制一个给定的对象时,你需要写

a = b.dup

Writing 写作

@app_session = session[@current_app[:uid]]

points to the same object so you should be fine. 指向同一个物体,所以你应该没事。

EDIT: you can verify this this way: 编辑:您可以这样验证:

irb(main):001:0> a = 1
=> 1
irb(main):002:0> b = a
=> 1
irb(main):004:0> p a.object_id
3
=> nil
irb(main):005:0> p b.object_id
3

Variables and constants are pointers to memory locations. 变量和常量是指向内存位置的指针。 Ruby does this by defaut, so you don't have to "emulate" the PVP behaviour by hand. Ruby通过defaut执行此操作,因此您无需手动“模拟”PVP行为。 Evidence: 证据:

a = "hi"
b = a
a.upcase!
puts a
# => "HI"
puts b
# => "HI"

As for your @app_session question, I'd do something like this: 至于你的@app_session问题,我会做这样的事情:

class ApplicationController < ActionController::Base
  def app_session
    session[@current_app[:uid]]
  end
end

This lets you call the method 'app_session', so that you can easily change the implementation later on. 这使您可以调用方法'app_session',以便稍后可以轻松更改实现。 (Say, if you find out that you need to use a constant instead of an instance variable, or whatever.) (比方说,如果你发现你需要使用常量而不是实例变量,或者其他什么。)

Agree with leethal and Keltia. 同意leethal和Keltia。 Just one thing to point out: 只需指出一点:

When you assign some string to a variable, you ALWAYS create a new String object, by doing so. 当您为变量分配一些字符串时,您总是通过这样做来创建一个新的String对象。

a = "foo"  # Create a new String object and make a refer this object.
b = "bar"  # Create a new String object and make b refer this object.
a = b      # Make b refer the object created in the first step.
a = "blah" # Create a new String object and make a refer this object. (!)
puts b     # But(!) b is still "foo", because it still refers the "foo" object.
# => "foo"

Isn't this the default for all ruby objects? 这不是所有ruby对象的默认值吗? It wouldn't make sense to copy an object every time. 每次复制一个对象都没有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM