2

我相信数组主要用于从方法返回多个值:

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.

4

2 回答 2

1

首先,你有一个语法错误。而不是这个:

[a, b] = [1, 2]

你应该使用:

a, b = [1, 2]

如果你想对哈希使用类似的语法,你可以这样做:

a, b = { "c" => 1, "d" => 2 }.values     # a => 1, b => 2

这实际上与数组版本相同,因为Hash#values按照它们插入哈希的顺序返回一个哈希值数组(因为 ruby​​ 哈希有一个很好的特性可以保留它们的顺序)

于 2015-12-25T19:16:00.940 回答
0

你所问的在语法上是不可能的。

您想要完成的事情是可能的,但您必须对其进行编码。一种可能的方法如下所示

hash = {"a" => 1, "b" => 2}

# Assign new keys
new_keys = ["c", "d"]
p [new_keys, hash.values].transpose.to_h
#=> {"c"=>1, "d"=>2}

# Assign new values
new_values = [3, 4]
p [hash.keys, new_values].transpose.to_h
#=> {"a"=>3, "b"=>4}

如果你真的想要一些看起来更简单的方法,你可以猴子补丁Hash类并定义新方法来操作数组的keysvalues。请注意,弄乱核心课程可能并不值得。无论如何,一个可能的实现如下所示。 使用风险自负。

class Hash
    def values= new_values
        new_values.each_with_index do |v, i|
            self[keys[i]] = v if i < self.size
        end
    end
    def keys= new_keys
        orig_keys = keys.dup
        new_keys.each_with_index do |k, i|
            if i < orig_keys.size
                v = delete(orig_keys[i])
                self[k] = v
                rehash
            end
        end
    end
end

hash = {"a" => 1, "b" => 2}

hash.values = [2,3]
p hash
#=> {"a"=>2, "b"=>3}

hash.keys = ["c", "d"]
p hash
#=> {"c"=>2, "d"=>3}

hash.keys, hash.values = ["x","y"], [9, 10]
p hash
#=> {"x"=>9, "y"=>10}

hash.keys, hash.values = ["x","y"], [9, 10]
p hash
#=> {"x"=>9, "y"=>10}

# *** results can be unpredictable at times ***
hash.keys, hash.values = ["a"], [20, 10]
p hash
#=> {"y"=>20, "a"=>10}
于 2015-12-25T20:16:00.300 回答