ruby 每个方法的动态变量

68de4m5k  于 2023-03-08  发布在  Ruby
关注(0)|答案(2)|浏览(354)

我有一个数组,我想迭代和创建动态变量。此外,我想循环它。任何想法如何实现它?
代码:

collection = ["s", "g", "l"]

collection.each do |variable_name|
   devan_'#{variable_name}' = ['h1', 'h2', 'h3']
   devan_'#{variable_name}'.each do |s1|
     puts "from #{variable_name} we got #{s1}"
   end
end

例外

syntax error, unexpected '=', expecting end
   devan_'#{variable_name}' = ['h1', 'h2', 'h3']
brvekthn

brvekthn1#

正如其他评论者所建议的,您可能需要一个哈希值来代替动态变量:

collection = ["s", "g", "l"]

collection.each do |key|
   devan[key] = ['h1', 'h2', 'h3']
   devan[key].each do |s1|
     puts "from #{key} we got #{s1}"
   end
end

使用哈希函数,你可以“免费”获得一个易于使用的方法库,否则使用动态变量会更麻烦。例如:

# Add an element to the array for the 's' key:
devan['s'].push 'h4'

# Add an element to the array for each key:
devan.each_key { |k| devan[k].push 'h5' }

# Print array length for each key:
devan.each { |k,v| puts v.length }
wz3gfoph

wz3gfoph2#

从块内部设置动态示例变量

在Ruby中,你所尝试的元编程类型必须与其他语言有所不同。在Ruby中,你不能简单地将一个字符串附加到赋值语句左手的变量名上,然后让它在当前命名空间中被识别为有效变量。当涉及到作用域门时,这就更成问题了。即使它起作用了,你最终得到的块局部变量也不会存在于当前块之外。
作为如何解决这种语言设计选择的一个示例,考虑这种动态方法,它利用Object#instance_variable_set来定义变量,利用Object#instance_variable_get来读取变量:

%w[s g l].map do |ext|
  varname = "@devan_#{ext}"
  instance_variable_set varname, ['h1', 'h2', 'h3']
  puts "#{varname} = #{instance_variable_get varname}"
end

[@devan_s, @devan_g, @devan_l]
#=> [["h1", "h2", "h3"], ["h1", "h2", "h3"], ["h1", "h2", "h3"]]

通过使用这种方法来设置或读取示例变量,你可以将字符串插值 * 作为参数 * 传递,而不是作为赋值或方法调用的左侧元素传递,你只需要在变量名前面加上一个@符号。
通过使用示例变量,你还可以确保新变量在本地块的作用域之外创建(并继续存在)。如果这不是你真正想要的,考虑使用Binding#local_variable_set和Binding#local_variable_get。

相关问题