在Ruby中循环的更简单方法

时间:2014-05-06 17:23:47

标签: ruby

我想做以下工作。

if not a; then puts a + " is not defined"
if not b; then puts b + " is not defined"
...
if not f; then puts f + " is not defined"

为了做到这一点,我必须输入很多单词。有没有更简单的方法来解决它?例如,

for i in %w[a b c d e f] do
  if not i; then puts i + " is not defined"
end

我知道上面的代码不起作用,但我仍然想知道是否有这么简单的方法。

1 个答案:

答案 0 :(得分:5)

显示有意义的局部变量,假设它们都已定义:

%w[a b c d e f].each{|i| puts "#{i} is not defined" unless eval i}

显示未定义的局部变量:

(%i[a b c d e f] - local_variables).each{|i| puts "#{i} is not defined"}