Sunday 15 August 2010

ruby - Can eval be avoided in nested [:a,:b].each{loops}? -



ruby - Can eval be avoided in nested [:a,:b].each{loops}? -

is there way utilize native ruby methods or maybe library did. , found eval , blew mind how implement solution.

i know eval isn't ideal because danger of arbitrary code injection. don't think happen in program, on safe side.

my first thought utilize tree structure, didn't work because don't know plenty trees , how iterate on them. tried nested hash, ended using eval populate too, , still had figure out how iterate on it.

#!/usr/bin/env ruby # programs generates guesses forgoten passwords guesses = [] passwords = [] # read user input , generate series of guesses. nth = 1 print "guess number 1:" while guess = gets nth += 1 print "guess number #{nth}:" guesses << guess.chomp.split('') end # generate look dequeuing guesses. first_string = "" second_string = "passwords << ''" letter = 101 # first ascii character counter = 0 guesses.count.times # dequeuing shifted_array = guesses.shift # fifo loops first_string += "#{shifted_array}.each{ |#{letter.chr}| " # concatenates each of permutations of guesses second_string += ".+(#{letter.chr})" letter += 1 # next ascii character counter += 1 end # adds ending braces final_string = first_string + second_string + ('}'*counter) # evaluates string populating passwords array print "\n" eval final_string passwords.each{|x| puts x }

enumerables quite powerful , worth learning. if understand problem correctly, same thing:

$stdin.each_line .map { |guess| guess.chomp.chars } .inject(&:product) .each { |pass| puts pass.join }

ruby eval

No comments:

Post a Comment