arrays - 用用户输入替换字符串中的单词 [RUBY]
问题描述
我试图弄清楚如何用用户字符串替换字符串中的单词。
将提示用户键入他们想要替换的单词,然后再次提示他们输入新单词。
例如,起始字符串是“Hello, World”。用户输入“World”,然后输入“Ruby”,最后输入“Hello, Ruby”。会打印出来。
到目前为止,我已经尝试使用 gsub 并且 [] 方法都没有奏效。有什么想法吗?
到目前为止,这是我的功能:
def subString(string)
sentence = string
print"=========================\n"
print sentence
print "\n"
print "Enter the word you want to replace: "
replaceWord = gets
print "Enter what you want the new word to be: "
newWord = gets
sentence[replaceWord] = [newWord]
print sentence
#newString = sentence.gsub(replaceWord, newWord)
#newString = sentence.gsub("World", "Ruby")
#print newString
end
解决方案
问题是当用户输入时也会抓住新行,所以你想把它去掉。我在控制台中做了这个愚蠢的测试用例
sentence = "hello world"
replace_with = gets # put in hello
replace_with.strip!
sentence.gsub!(replace_with, 'butt')
puts sentence # prints 'butt world'
推荐阅读
- javascript - 通过ajax动态输入直到嚎叫 - 输入不起作用
- java - 使用带有 Spring Boot 2 的实体管理器时,没有类型为“javax.persistence.EntityManager”的合格 bean
- javascript - 如何在 c# 中使用 chromium 网络浏览器获取 javascript 的返回值
- php - WHMCS 自定义域注册模块
- node.js - Firebase Cloud Firestore 如何设置 snapShotOptions
- c# - 有没有更好的方法来编写 LINQ 函数?
- javascript - 在 js 对象中使用 getter 函数,为什么我的代码不起作用?
- django - 在 django 项目中定位和读取特定 .env 文件时出错
- java - 调用 Java 类方法来处理 EditTexts 的值
- angular - 如何在下次提交表单之前隐藏错误消息