简体   繁体   中英

using a string (from gets) directly as a variable name

Starting out my Towers of Hanoi assignment, I have

a = [6,5,4,3,2,1]
b = []    
c = []

puts "Type a, b, or c"
from = gets.chomp
# the user types a lower-case a
popped = from.pop

Now this obviously fails because pop is not a string method.

So other than

if from == a
    popped = a.pop
elsif from == b
    popped = b.pop

, is there a nice ruby shortcut to get the pop I intend?

You can use eval :

a = [6,5,4,3,2,1]
b = []    
c = []

puts "Type a, b, or c"
from = gets.chomp
popped = eval(from).pop

But eval is typically seen as a bad idea for security, performance, and debugging reasons.

options = {
  :a => [6,5,4,3,2,1]
  :b => []    
  :c => []
}

puts "Type a, b, or c"
from = gets.chomp
popped = options[from.to_sym].pop

I have to strongly advise you avoid the use of the method using eval above, as it allows the user to input arbitrary code. Use a hash instead to store all your options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM