“="和“="有什么区别?&“="和“@variable"、“@@variable"和“:变量"在红宝石? [英] What's the difference between "=" & "=>" and "@variable", "@@variable" and ":variable" in ruby?
问题描述
我知道这些是 Rails 的基础知识,但我仍然不知道 =
符号和 =>
之间的全部区别以及 @ 之间的区别rails 中的 some_variable
、@@some_variable
和 :some_variable
.
I know these are the basics of rails but i still don't know the full difference between =
sign and =>
and the difference between @some_variable
, @@some_variable
and :some_variable
in rails.
谢谢.
推荐答案
好的.
=
和 =>
运算符之间的区别在于,第一个是赋值,第二个表示散列(关联数组)中的关联.所以 { :key =>'val' }
是说创建一个关联数组,其中 :key
是键,'val'
是值".如果你想听起来像一个 Rubyist,我们称之为hashrocket".(信不信由你,这不是 Ruby 中最奇怪的运算符;我们还有 <=>
,或太空船运算符".)
The difference between the =
and the =>
operators is that the first is assignment, the second represents an association in a hash (associative array). So { :key => 'val' }
is saying "create an associative array, with :key
being the key, and 'val'
being the value". If you want to sound like a Rubyist, we call this the "hashrocket". (Believe it or not, this isn't the most strange operator in Ruby; we also have the <=>
, or "spaceship operator".)
您可能会感到困惑,因为在方法中可以使用一些快捷方式,如果最后一个参数是散列,则可以省略波浪括号 ({}
).所以调用 render :partial =>'foo'
基本上是调用 render 方法,传入一个带有单个键/值对的哈希值.正因为如此,你经常看到一个散列作为最后一个参数来排序一个穷人的可选参数(你在 JavaScript 中也看到了类似的东西).
You may be confused because there is a bit of a shortcut you can use in methods, if the last parameter is a hash, you can omit the squiggly brackets ({}
). so calling render :partial => 'foo'
is basically calling the render method, passing in a hash with a single key/value pair. Because of this, you often see a hash as the last parameter to sort of have a poor man's optional parameters (you see something similar done in JavaScript too).
在 Ruby 中,任何普通单词都是局部变量.所以foo
在方法内部是一个作用域为方法级别的变量.用 @
前缀变量意味着将变量作用于实例.所以@foo
在方法中是一个实例级别.
In Ruby, any normal word is a local variable. So foo
inside a method is a variable scoped to the method level. Prefixing a variable with @
means scope the variable to the instance. So @foo
in a method is an instance level.
@@
表示类变量,表示@@
变量在类的作用域内,以及所有实例.
@@
means a class variable, meaning that @@
variables are in scope of the class, and all instances.
:
表示符号.Ruby 中的符号是一种特殊的字符串,暗示它将用作键.如果您来自 C#/Java,它们的使用类似于枚举的关键部分.还有一些其他的区别,但基本上任何时候你要把一个字符串当作任何类型的键,你都可以使用符号来代替.
:
means symbol. A symbol in Ruby is a special kind of string that implies that it will be used as a key. If you are coming from C#/Java, they are similar in use to the key part of an enum. There are some other differences too, but basically any time you are going to treat a string as any sort of key, you use a symbol instead.
这篇关于“="和“="有什么区别?&“="和“@variable"、“@@variable"和“:变量"在红宝石?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!