如何组合2个数组并将元素设置为变量?

时间:2018-08-10 08:33:49

标签: arrays ruby variables elements

items = ["pickle", "tuna", "pasta_sauce", "beans", "soup"]
price = [6, 5, 3, 2, 2]
items = price

我想打个电话,例如:pickle #=> 6; tuna # => 5,依此类推。

3 个答案:

答案 0 :(得分:1)

不可能动态创建局部变量。

您可以执行类似eval "abc = 123; puts abc"的操作,但此后abc仍未定义。

可以更改现有局部变量的值:

items = ["pickle", "tuna", "pasta_sauce", "beans", "soup"]
price = [6, 5, 3, 2, 2]

pickle = nil
tuna = nil
pasta_sauce = nil
beans = nil
soup = nil

local_binding = binding
items.zip(price).each do |var, val|
  local_binding.local_variable_set var, val
end

puts pasta_sauce
# outputs 3

您可能想做些不同的事情。例如,您可以动态创建实例变量:

items = ["pickle", "tuna", "pasta_sauce", "beans", "soup"]
price = [6, 5, 3, 2, 2]

items.zip(price).each do |var, val|
  instance_variable_set "@#{var}", val
end

puts @pasta_sauce
# outputs 3

答案 1 :(得分:1)

您可能更适合将两个数组转换为哈希以进行访问,而不是使用元编程来设置变量(尽管@KimmoLehto提供了一个很好的答案,如果您选择该路线)。

作为创建两个数组的哈希的一种更简单的方法:

my_hash = Hash[items.zip(price)]
# or
my_hash = items.zip(price).to_h

items.zip(price)合并数组(请参阅:zip):

[["pickle", 6], ["tuna", 5], ["pasta_sauce", 3], ["beans", 2], ["soup", 2]]

并使用Hash::[]to_h转换为哈希:

{"pickle"=>6, "tuna"=>5, "pasta_sauce"=>3, "beans"=>2, "soup"=>2}

然后您可以使用标准哈希语法访问密钥:

my_hash['pickle'] # => 6

或如果希望使用.访问变量,则转换为和OpenStruct

my_open_struct = OpenStruct.new(items.zip(price).to_h)
my_open_struct.pickle # => 6

希望有帮助。

答案 2 :(得分:0)

您可以创建一个新的哈希来聚合这些数组。

<ContentWithTargetPath Include="references\libDependencies\linux64\libcvextern.so" Condition=" '$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Linux)))' ">
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  <TargetPath>libcvextern.so</TargetPath>
</ContentWithTargetPath>


<ContentWithTargetPath Include="references\libDependencies\linux64\libSQLite.Interop.so" Condition=" '$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Linux)))' ">
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  <TargetPath>libSQLite.Interop.so</TargetPath>
</ContentWithTargetPath>


<ContentWithTargetPath Include="references\libDependencies\win64\cvextern.dll" Condition=" '$(OS)' == 'Windows_NT' ">
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  <TargetPath>cvextern.dll</TargetPath>
</ContentWithTargetPath>