# 賦值

``````# 賦值給一個區域變數
local = 1

# 賦值給一個實例變數
@instance = 2

# 賦值給一個類別變數
@@class = 3
``````

``````local += 1  # 等同於 local = local + 1

# 這些運算子都套用上述的規則：
# +, -, *, /, %, |, &, ^, **, <<, >>

# 這裡還有兩個不太一樣的規則
local ||= 1 # 等同於 local || (local = 1)
local &&= 1 # 等同於 local && (local = 1)
``````

``````# Set 存取子 (Setter)
person.name=("John")

# 也可以寫成這樣：
person.name = "John"

# 使用索引的 Set 存取子來賦值
objects.[]=(2, 3)

# 也可以寫成這樣：
objects[2] = 3

# 下面這個並「不是賦值」，但也有類似的語法糖：
objects.[](2, 3)

# 也可以寫成這樣：
objects[2, 3]
``````

``````person.age += 1        # 等同於 person.age = person.age + 1

person.name ||= "John" # 等同於 person.name || (person.name = "John")
person.name &&= "John" # 等同於 person.name && (person.name = "John")

objects[1] += 2        # 等同於 objects[1] = objects[1] + 2

objects[1] ||= 2       # 等同於 objects[1]? || (objects[1] = 2)
objects[1] &&= 2       # 等同於 objects[1]? && (objects[1] = 2)
``````

# Chained assignment

You can assign the same value to multiple variables using chained assignment:

``````a = b = c = 123

# Now a, b and c have the same value:
a # => 123
b # => 123
c # => 123
``````

The chained assignment is not only available to local variables but also to instance variables, class variables and setter methods (methods that end with `=`).

# 多項賦值

``````name, age = "Crystal", 1

# 相當於：
temp1 = "Crystal"
temp2 = 1
name  = temp1
age   = temp2
``````

``````a = 1
b = 2
a, b = b, a
a #=> 2
b #=> 1
``````

``````name, age, source = "Crystal, 123, GitHub".split(", ")

# 等同於下面的做法：
temp = "Crystal, 123, GitHub".split(", ")
name = temp[0]
age = temp[1]
source = temp[2]
``````

``````person.name, person.age = "John", 32

# Same as:
temp1 = "John"
temp2 = 32
person.name = temp1
person.age = temp2
``````

``````objects[1], objects[2] = 3, 4

# Same as:
temp1 = 3
temp2 = 4
objects[1] = temp1
objects[2] = temp2
``````