【问题标题】:repeat the code once and not to every element - .each method - Ruby重复代码一次,而不是对每个元素 - .each 方法 - Ruby
【发布时间】:2021-05-27 12:53:48
【问题描述】:

我有一个小程序,它接收用户输入的文本,询问要编辑的单词,然后编辑该单词:

puts "Text to search through: "
text = gets.chomp
puts "Word to redact: "
redact = gets.chomp

words = text.split(" ")

words.each do |word|
  if word != redact
    print "no such word. "
  else
    print "REDACTED ! "
  end
end

但是,我不喜欢输出,因为使用 .each 方法会重复并且看起来不整洁。

Text to search through: 
this is my text
Word to redact: 
is
no such word. REDACTED ! no such word. no such word. 

阻止它为数组的每个元素重复答案并打印“已编辑!”的解决方案是什么?只有一次?

或者当没有要编辑的词时,而不是像这样对每个元素重复答案:

Text to search through: 
this is my text
Word to redact: 
no
no such word. no such word. no such word. no such word.

只打印一次“No such word”。谢谢。

【问题讨论】:

  • "然后编辑那个词" – 你的代码只打印“REDACTED !”无需实际更改输入。
  • 其实你是对的,它并不是我想要它做的事情
  • 您可能想看看gsub! - 如果没有进行任何更改,bang 变体返回nil

标签: arrays ruby each


【解决方案1】:

您可以使用Array#include? 方法检查单词是否包含编辑:

if words.include?(redact)
  print "REDACTED !"  
else
  print "no such word."
end

【讨论】:

  • ...或print words.include?(redact) ? 'REDACTED !' : 'no such word'
  • 但是我如何使输出成为所有单词,而只是需要更改的单词被更改为字符串“REDACTED!” ? @eux
  • 你可以用String#sub替换redcattext.sub(redcat, "REDCATED !")
猜你喜欢
  • 2017-11-12
  • 2021-11-23
  • 2013-07-30
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 2011-09-18
  • 2011-03-01
  • 2020-12-04
相关资源
最近更新 更多