Is there a way to do this without eval?
I don't see eval used by others much in ruby, so I'm assuming this can be done without it. But I don't see how.
(1..9).each { |n|
eval "user_#{n} = prefix << '_' &开发者_开发技巧lt;< user_#{n} if user_#{n}"
}
Rewrite your code using a hash instead of local variables and you can ditch eval:
(1..9).each { |n|
user[n] = prefix << '_' << user[n] if user[n]
}
BTW, I think you didn't want to use <<
above as it will modify your prefix
as well.
If you want to implement this as an array, you can try
users.map! do |user|
user ? "#{prefix}_#{user}" : nil
end
assuming that users
is already defined.
You can define a method dynamically using ruby's define_method.
You can replace eval
-based statements with a define_method
enclosed in a class_eval
.
But, it depends on the situation. It might be overkill to replace eval
with a dynamic method.
You need to provide more context for your question to get a better answer.
精彩评论