【发布时间】:2015-03-09 05:23:47
【问题描述】:
在 PHP 中,我可以通过设置 $variable_name = foo 和 echo $$variable_name 之类的东西来动态访问变量,然后 echo 的值将是 foo。但我不清楚如何在 Ruby 中做到这一点。在 PHP 中,我可以做这样的事情;在数组中分配变量名并遍历它们:
# Set string values.
$value_one = 'a one';
$value_two = 'and a two';
$value_three = 'and a three';
# Set array of variable names.
$process_items_array = array('value_one', 'value_two', 'value_three');
# Roll through the values.
foreach ($process_items_array as $value) {
$$value = do_something($$value) . '<br />';
}
# A simple function for example’s sake.
function do_something ($value = null) {
return strtoupper($value);
}
但是在 Ruby 中,什么是等价的?例如,我已经尝试过,但没有一个项目按预期工作;请注意,这是在非类结构中使用self. 引用所指出的伪代码:
# Set string values.
value_one = 'a one';
value_two = 'and a two';
value_three = 'and a three';
# Set array of variable names.
process_items_array = ['value_one', 'value_two', 'value_three']
# Roll through the values.
process_items_array.each { |value|
self.send("#{value}").to_sym = do_something value.try(self.send("#{value}").to_sym)
}
# A simple function for example’s sake.
def do_something value
value = value.try(:strip)
value = nil if value.blank?
value.upcase
end
注意我尝试使用instance_variable_get、[send][2] 和to_sym;我基本上希望有些事情会奏效,但似乎没有任何效果。我应该怎么做?
【问题讨论】:
-
我确定您使用它的目的是什么,但这似乎不是一个人应该在 Ruby 中做的事情 - 可能有一种更强大的方法可以用一点点重新设计。
-
这就是发明字典和哈希映射的目的——通过另一个(可变的)键来引用一个值。
-
@JavaNut13 虽然我很欣赏你所说的,但现实是我无法重构我没有创建的整个代码库,所以我必须简单地使用我拥有的代码库并以我最好的方式处理它能够。如果客户认为重构值得花时间/精力,我会考虑沿着这条路走下去。
标签: ruby string variable-assignment