I need to replace placeholders NOUN, VERB, ADJ, and ADV in a file solution09.txt with user input.
Madlib solution09.txt:
One day I was watching my son [ADV] play with his [NOUN]. He was pretending the [NOUN] were [ADJ]. After a few minutes he was pretending to [VERB], because one of the [NOUN] drove away. When i asked him about it he [ADV] said, umm it's funny when [NOUN] [VERB] because [NOUN] can't really [VERB].
I think I successfully put the file into a string, but I have to read the string, and replace the placeholders with user input. Once I replace, I need to output the new madlib. I'm getting the user input into variables, but I'm not sure how to correctly replace the placeholder with the users input.
Current code:
file = File.open("solution09.txt", "r")
contents = file.read
puts "Enter a noun: "
noun = gets.chomp
puts "Enter a verb: "
verb = gets.chomp
puts "Enter an adjective: "
adj = gets.chomp
puts "Enter an adverb: "
adv = gets.chomp
if file.include?('NOUN')
file1= file.gsub("[NOUN]", noun, "[VERB]", verb, "ADJ", adj, "ADV", adv)
end
You can also build a replacement hash:
filename = "solution09.txt"
contents = File.read(filename)
replacements = {}
puts "Enter a noun: "
replacements['[NOUN]'] = gets.chomp
puts "Enter a verb: "
replacements['[VERB]'] = gets.chomp
puts "Enter an adjective: "
replacements['[ADJ]'] = gets.chomp
puts "Enter an adverb: "
replacements['[ADV]'] = gets.chomp
And pass it to gsub:
contents.gsub(Regexp.union(replacements.keys), replacements)
Regexp.union creates a pattern that matches any of the given keys.
Your code should look like
filename = "solution09.txt"
contents=File.read(filename)
puts "Enter a noun: "
noun=gets.chomp
puts "Enter a verb: "
verb=gets.chomp
puts "Enter an adjective: "
adj=gets.chomp
puts "Enter an adverb: "
adv=gets.chomp
if contents.include?('NOUN')
{ "\[NOUN\]" => noun,
"\[VERB\]" => verb,
"\[ADJ\]" => adj,
"\[ADV\]" => adv
}.each do |key, value|
contents.gsub!(key, value)
end
File.open(filename, "w") { |f| f << contents }
end
You need separate operation for read and write. There are other ways to do this
You can see how to do with single file pointer https://stackoverflow.com/a/10173112/1380263
You can also use ruby methods which interact with shell and use sed command (system, backticks, peopen)
Really depends on what suits your situation the best
file = File.read("solution09.txt")
.gsub(/\[(NOUN|VERB|ADJ|ADV)\]/) do
part = case $1
when "NOUN" then "a noun"
when "VERB" then "a verb"
when "ADJ" then "an adjective"
when "ADV" then "an adverb"
end
puts "Enter #{part}: "
gets.chomp
end
Related
I have some troubles with my code using Ruby. its just for a terminal program, so no website or anything.
In my code I Will have the user create a login. Then I will have the user to login, but I cant seem to figure out how to check if password or username is correct.
The program should compare whatever the user types in as a username/password with the file (userdatabase) - I think i got that right.
Now I am trying to stop the user if the input is not found in the user database, using a while loop, but i cant seem to make that work.
Code:
puts "What will be your user name?"
username = gets.chomp
puts "What will be your password?"
password = gets.chomp
puts "Please repeat your password."
passwordsafe = gets.chomp
f = File.new("student.txt", "w+")
f.puts username + ";" + password + ";" + passwordsafe
f.close
puts "well done, you have created a new user."
lines = IO.readlines("student.txt")
lines.each{|line| print(line)}
puts "now you need to login."
puts "What is your username?"
username = gets.chomp
File.open("student.txt") do |f|
f.any? do |line|
while line.include?(username)
end
end
elsif puts "Sorry your username was incorrect"
end
#lines = IO.readlines("student.txt")
#lines.each{|line| (line)}
puts "what is your password?"
password = gets.chomp
The while is unnecessary.
The username check currently like this:
File.open("student.txt") do |f|
f.any? do |line|
while line.include?(username)
end
end
Could be like this:
File.open("student.txt").each_line.any? do |line|
line.include?(username)
end
Or collapsed to a single line like this:
File.open("student.txt").each_line.any?{ |l| l.include?(username) }
Check the docs on the any? method to make sure you understand what it's expecting: http://ruby-doc.org/core-2.4.2/Enumerable.html#method-i-any-3F
As for the rest of the syntax errors, I'll leave those up to you ;)
I'm making a basic "Helper" program..
Anyway here's the code:
def sayHelp()
puts "------------List of help and commands-------------"
puts "Help-- Shows a list of commands."
puts "Start [PROGRAM] (PROGRAM ARGS)-- Starts the specified program."
return true
end
version = "1.0"
ccommand = ""
puts "Welcome to RubyBot " + version + "."
puts "------------------------------------"
sleep(3)
system "clear" or system "cls"
puts "Enter \"help\" for a list of commands."
puts "Please enter a command: "
ccommand = gets
if ccommand == "help"
sayHelp()
else
puts "Not right bro"
end
I go ahead and run this and enter help but it just chucks Not right bro up at me.. What am I doing wrong?
ccommand = gets
The string returned by gets has a trailing new line character, remove it and it will work:
ccommand = gets.chomp
I am trying to create a find and replace script in ruby. But I cannot figure out how to write to the same file twice when there are two conditions matched (2 different regex patterns are found and need to be replaced in the same file) I can get it to provide 2 copies of the file concatonated with only changes made from one condition in each.
Here is my code (Specifically pattern3 and pattern4):
print "What extension do you want to modify? "
ext = gets.chomp
if ext == "py"
print("Enter password: " )
pass = gets.chomp
elsif ext == "bat"
print "Enter drive letter: "
drive = gets.chomp
print "Enter IP address and Port: "
ipport = gets.chomp
end
pattern1 = /'Admin', '.+'/
pattern2 = /password='.+'/
pattern3 = /[a-zA-Z]:\\(?i:dir1\\dir2)/
pattern4 = /http:\/\/.+:\d\d\d\d\//
Dir.glob("**/*."+ext).each do |file|
data = File.read(file)
File.open(file, "w") do |f|
if data.match(pattern1)
match = data.match(pattern1)
replace = data.gsub(pattern1, '\''+pass+'\'')
f.write(replace)
puts "File " + file + " modified " + match.to_s
elsif data.match(pattern2)
match = data.match(pattern2)
replace = data.gsub(pattern2, 'password=\''+pass+'\'')
f.write(replace)
puts "File " + file + " modified " + match.to_s
end
if data.match(pattern3)
match = data.match(pattern3)
replace = data.gsub(pattern3, drive+':\dir1\dir2')
f.write(replace)
puts "File " + file + " modified " + match.to_s
if data.match(pattern4)
match = data.match(pattern4)
replace = data.gsub(pattern4, 'http://' + ipport + '/')
f.write(replace)
puts "File " + file + " modified " + match.to_s
end
end
end
end
f.truncate(0) makes things better but truncates the first line since it concatonates from the end of the 1st modified portion of the file.
Try writing file only once after all substitutions:
print "What extension do you want to modify? "
ext = gets.chomp
if ext == "py"
print("Enter password: " )
pass = gets.chomp
elsif ext == "bat"
print "Enter drive letter: "
drive = gets.chomp
print "Enter IP address and Port: "
ipport = gets.chomp
end
pattern1 = /'Admin', '.+'/
pattern2 = /password='.+'/
pattern3 = /[a-zA-Z]:\\(?i:dir1\\dir2)/
pattern4 = /http:\/\/.+:\d\d\d\d\//
Dir.glob("**/*.#{ext}").each do |file|
data = File.read(file)
data.gsub!(pattern1, "'#{pass}'")
data.gsub!(pattern2, "password='#{pass}'")
data.gsub!(pattern3, "#{drive}:\\dir1\\dir2")
data.gsub!(pattern4, "http://#{ipport}/")
File.open(file, 'w') {|f| f.write(data)}
end
file_1 = File.open('Data_family.txt', 'r')
user1 = go
while user1 != "stop"
print "whould you like to create: "
user1 = gets.chomp
print "what is your relation: "
relation = gets.chomp
file_1.syswrite "this is your " + relation
file_1.syswrite "\n"
end
file_1.close
am am confused as to why by block does not run. I whould like to create a family tree data base yet it will not allow me to add data to the file i opened
I think you're trying to do something like:
#!/usr/bin/eval ruby
File.open('Data_family.txt', 'w') do |file_1|
loop do
print "Who would you like to create: "
user1 = gets.chomp
break if user1 == "stop"
print "what is your relation: "
relation = gets.chomp
file_1.puts "this is your " + relation
end
end #File autocloses at the end of the block
My source code:
books = {
Harry_Potter: 5,
Steve_Jobs: 10
}
def finder(bookName)
books.each {
|n| if n == bookName
puts "Are you sure you want to #{choice} #{n}?"
confirmAction = gets.chomp
if confirmAction == "yes"
case choice
when "update"
puts "Enter the new name:"
newName = gets.chomp.to_sym
books[newName.to_sym] = books.delete(n)
puts "Update the rating for #{newName}:"
newRating = gets.chomp.to_i
books[newName.to_sym] = newRating.to_i
puts "Successfully updated #{newName} with rating of #{newRating}"
when "delete"
books.delete(n)
else puts "Invalid option!"
end
else puts "Invalid book name."
end
end
}
end
puts "What would you like to do?\n[Add] [Update] [Delete] [View]"
action = gets.chomp.capitalize
case action
when "Add"
puts "Enter the new book name:"
title = gets.chomp.to_sym
puts "Please rate the book [1-10]:"
rating = gets.chomp.to_i
books[title.to_sym] = rating.to_i
puts "Successfully added #{title} with rating of #{rating}"
puts books
when "Update"
choice = "update"
puts "Enter the name of the book:"
bookName = gets.chomp.to_sym
finder(bookName)
when "Delete"
choice = "delete"
puts "Enter the name of the book:"
bookName = gets.chomp.to_sym
finder(bookName)
when "View"
choice = "view"
puts books.each {
|k, v| puts "#{k}: #{v}"
}
end
Whenever I use add option and add something it works. But once I exit and re-open the program, it doesn't show books that I've added using the add option, it returns to the default list.
I need Ruby to save all the changes permanently.
You have to save your objects yourself, e.g. using YAML:
require 'yaml'
File.write('data.yml', YAML.dump(books))
The contents of "data.yml" will be:
---
:Harry_Potter: 5
:Steve_Jobs: 10
To read the file use:
books = YAML.load(File.read('data.yml'))
#=> {:Harry_Potter=>5, :Steve_Jobs=>10}
Well, you could use Maglev which is a ruby interpreter based on the GemStone/S Object Server which will be able to store your books persistently (by setting a reference to your books Hash and Maglev.commit_transaction). However this might be a bit of an overkill for your purposes :-)