我相信数组主要用于从方法返回多个值:
def some_method
return [1, 2]
end
[a, b] = some_method # should yield a = 1 and b = 2
我认为这是 Ruby 提供的一种语法糖。例如,我们可以用哈希得到类似的结果吗?
def some_method
return { "a" => 1, "b" => 2 }
end
{"c", "d"} = some_method() # "c" => 1, "d" => 2
我正在寻找结果{ "c" => 1, "d" => 2 }
,这显然不会发生。有没有其他方法可以做到这一点?我知道我们可以从该方法返回一个哈希并存储它并像这样使用它
def some_method
return {"a" => 1, "b" => 2}
end
hash = some_method()
只是好奇是否有另一种类似于使用数组但使用哈希的方法......
我认为提出问题的更简单方法是......
# If we have a hash
hash = {"a" => 1, "b" => 2}
# Is the following possible
hash = {2, 3} # directly assigning values to the hash.
OR
# another example
{"c", "d"} = {2, 3} # c and d would be treated as keys and {2, 3} as respective values.