Ruby:如何用户输入创建堆栈?

时间:2015-01-21 16:33:21

标签: ruby-on-rails ruby arrays input split

这里的ruby-baby总数,我正试图使用​​this Codecademy Tutorial来解决它。 试图更好地理解它我会在尝试时给出额外的问题,但是我不明白为什么。

所以 - 手头的程序非常简单:它用一个单词“删除”替换输入中的单个用户定义的单词。 现在:我想将编辑的单词列表扩展到用户喜欢的数量,而不仅仅是一个。

这是我的尝试:

puts "Please enter your text here: "
text = gets.chomp
puts "Which words would you like to redact? "
redact = gets.chomp

words = text.split(" ")
censorlist = redact.split(" ") 

=begin 
How do I build an array out of this .split to access all the words separately in my if-condition?
=end

words.each do |word|
  if word != censorlist
    print word + " "
  else 
    print "REDACTED " 
end   
end

很抱歉,如果这个问题太基础了,不能在这里问一下,但我已经旋转了一段时间,而我在其他地方找到的所有答案对我来说都没有意义。我只是不知道如何访问我用.split制作的数组。 谢谢!

N。

1 个答案:

答案 0 :(得分:0)

# ask the user for the text to process
puts "Please enter your text here: "
text = gets.chomp

# ask for words to redact. `split()` will split into words by default
puts "Which words would you like to redact? "
redact = gets.chomp.split

redact.each do |word|
  # instead of printing each word, we CHANGE the text supplied
  text.gsub!(word, 'REDACTED')
end
puts text

有关详细信息,请参阅String#splitString#gsub!

更新:正如@engineersmnky指出的那样,这是一种更简单的方法:

puts "Please enter your text here: "
text = gets.chomp
puts "Which words would you like to redact? "
redact = gets.chomp

# create a Regular Expression matching all words to redact
regex = /#{redact.gsub(' ', '|')}/
puts text.gsub(regex, 'REDACTED')