a string output is not showing ruby - ruby

I'm tried these ruby code lines to run in sublimeText3 but I dont get any error even in view ->show console. Show result shows me that the coding is building, but I couldn't see any output there. The below code is what I'm trying.
guess.rb
words = ['foobar', 'baz', 'quux']
secret = words[rand(3)]
print "guess? "
while guess = STDIN.gets
guess.chop!
if guess == secret
puts "You win!"
break
else
puts "Sorry, you lose."
end
print "guess? "
end
puts "The word was ", secret, "."

Since the Sublime Text console does not accept any input, you need to install package like SublimeREPL. You can launch it from Tools > SublimeREPL > Ruby.

Related

ex17.rb:5:in `open': no implicit conversion of nil into String (TypeError) from ex17.rb:5:in `<main>'

I am going through "Ruby the Hard Way". Typing in the exercises as instructed. Got to Exercise 17 and as far as i can tell typed in correctly but when i run it get this error:
ex17.rb:5:in open': no implicit conversion of nil into String (TypeError) from ex17.rb:5:in '
Can anyone tell me what is wrong here?
put the 5 in the code below to show line 5. I think the error means it is in line 5.
This is the exercise:
from_file, to_file = ARGV
puts "Copying from #{from_file} to #{to_file}"
5 in_file = open(from_file)
indata = in_file.read
puts "The input file is #{indata.length} bytes long"
puts "Does the output file exist? #{Fileexist?(to_file)}"
puts "Ready , hit RETURN to continue, CTRL-C to abort."
$stdin.gets
out_file = open(to_file, 'w')
out_file.write(indata)
puts "Alright, all done."
out_file.close
in_file.close
I was running this on the Terminal, I ran it as >ruby ex17.rb, without submitting a filename afterwards. So, on the prompt, I should have submitted it as >ruby ex17.rb with a file name.

A basic "Helper" program not working as expected

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

Ruby: gets.chomp with default value

Is there some simple way how to ask for a user input in Ruby WHILE providing a default value?
Consider this code in bash:
function ask_q {
local PROMPT="$1"
local DEF_V="$2"
read -e -p "$PROMPT" -i "$DEF_V" REPLY
echo $REPLY
}
TEST=$(ask_q "Are you hungry?" "Yes")
echo "Answer was \"$TEST\"."
Can you achieve similar behaviour with Ruby's gets.chomp?
function ask_q(prompt, default="")
puts prompt
reply = gets.chomp() # ???
return reply
def
reply = ask_q("Are you hungry?", "Yes")
I understand I can sort replicate the functionality in Ruby this way ...
def ask_q(prompt, default="")
default_msg = (default.to_s.empty?) ? "" : "[default: \"#{default}\"]"
puts "${prompt} ${default}"
reply = gets.chomp()
reply = (default.to_s.empty?) ? default : reply
return reply
end
... but it does not seem very pretty. I also need to show the default value manually and the user needs to retype it in the prompt line, if he wants to use modified version of it (say yes! instead of yes).
I'm starting with Ruby now, so there may be a lot of syntax mistakes and I also may be missing something obvious ... Also, I googled a lot but surprisingly found no clue.
TL; DR
To make the question clearer, this is what you should see in terminal and what I am able to achieve in bash (and not in Ruby, so far):
### Terminal output of `reply=ask_q("Are you hungry?" "Yes")`
$ Are you hungry?
$ Yes # default editable value
### Terminal output of `reply=ask_q("What do you want to eat?")`
$ What do you want to eat?
$ # blank line waiting for user input, since there is no second parameter
And the actual situation: I am building bootstrap script for my web apps. I need to provide users with existing configuration data, that they can change if needed.
### Terminal output of `reply=ask_q("Define name of database." "CURR_DB_NAME")`
I don't think it's that fancy functionality, that would require switch to GUI app world.
And as I've said before, this is quite easily achievable in bash. Problem is, that other things are pure pain (associative arrays, no return values from functions, passing parameters, ...). I guess I just need to decide what sucks the least in my case ...
You need to do one of two things:
1) Create a gui program.
2) Use curses.
Personally, I think it's a waste of time to spend any time learning curses. Curses has even been removed from the Ruby Standard Library.
A GUI program:
Here is what a gui app looks like using the Tkinter GUI Framework:
def ask_q(prompt, default="")
require 'tk'
root = TkRoot.new
root.title = "Your Info"
#Display the prompt:
TkLabel.new(root) do
text "#{prompt}: "
pack("side" => "left")
end
#Create a textbox that displays the default value:
results_var = TkVariable.new
results_var.value = default
TkEntry.new(root) do
textvariable results_var
pack("side" => "left")
end
user_input = nil
#Create a button for the user to click to send the input to your program:
TkButton.new(root) do
text "OK"
command(Proc.new do
user_input = results_var.value
root.destroy
end)
pack("side" => "right", "padx"=> "50", "pady"=> "10")
end
Tk.mainloop
user_input
end
puts ask_q("What is your name", "Petr Cibulka")
Calling a function in a bash script from ruby:
.../bash_programs/ask_q.sh:
#!/usr/bin/env bash
function ask_q {
local QUESTION="$1"
local DEFAULT_ANSWER="$2"
local PROMPT="$QUESTION"
read -p "$PROMPT $DEFAULT_ANSWER" USERS_ANSWER #I left out the -i stuff, because it doesn't work for my version of bash
echo $USERS_ANSWER
}
ruby_prog.rb:
answer = %x{
source ../bash_programs/ask_q.sh; #When ask_q.sh is not in a directory in your $PATH, this allows the file to be seen.
ask_q 'Are you Hungry?' 'Yes' #Now you can call functions defined inside ask_q.sh
}
p answer.chomp #=> "Maybe"
Using curses:
require 'rbcurse/core/util/app'
def help_text
<<-eos
Enter as much help text
here as you want
eos
end
user_answer = "error"
App.new do #Ctrl+Q to terminate curses, or F10(some terminals don't process function keys)
#form.help_manager.help_text = help_text() #User can hit F1 to get help text (some terminals do not process function keys)
question = "Are You Hungry?"
default_answer = "Yes"
row_position = 1
column_position = 10
text_field = Field.new(#form).
name("textfield1").
label(question).
text(default_answer).
display_length(20).
bgcolor(:white).
color(:black).
row(row_position).
col(column_position)
text_field.cursor_end
text_field.bind_key(13, 'return') do
user_answer = text_field.text
throw :close
end
end
puts user_answer

Ruby win32ole - Can't replace text in word document

I'm trying to replace text in a document like so:
require 'win32ole'
def replace_doc(doc, find, repl)
begin
word = WIN32OLE.new('Word.Application')
word.Visible = true
doc = word.Documents.Open(doc)
word.Selection.HomeKey(unit=6)
finder = word.Selection.Find
finder.Text = "[#{find}]"
while word.Selection.Find.Execute
word.Selection.TypeText(text=repl)
end
doc.SaveAs(doc)
doc.Close
rescue Exception => e
puts e.message
puts "Unable to edit file."
end
end
def main()
puts "File: "
doc = gets.chomp()
puts "Find: "
find = gets.chomp()
puts "Replace with: "
repl = gets.chomp()
replace_doc(doc, find, repl)
end
main()
I'm running Ruby 2.0 on Windows XP. The WINWORD.exe process starts (I see it in task manager), and no exception is raised. However, when I go to the document, none of the text I expect to be replaced -- is. What is going on? I've copied the code (except for a few things) from here.
It's hard to say without the actual word document and input data you're using, but I suspect that the square brackets in finder.Text are your issue. As your program is now, entering foo for the find text would search for [foo] in your word document, not plain foo. Note that in the post you linked. There are actual square brackets in the example word document (it contains [date] etc.)

Ruby command line program that saves and updates users/preferences

I'm building an application that takes in stdin to save a user and their preferences. Should I write the stdin to a text file and save the user input there?
commandline.rb
class CommandLine
def initialize(filename)
#file = File.open(filename, 'w')
end
def add_user(input)
#file = File.open('new_accounts.txt', 'r+')
#file.write(input)
puts input
end
def run
puts "Welcome to the Command Line Client!"
command = ''
while command != 'quit'
printf "enter command: "
input = gets.chomp
parts = input.split
command = parts[0]
case command
when 'quit' then puts 'Goodbye!'
when '-a' then add_user(parts[1..-1].join(" "))
else
puts 'Invalid command #{command}, please try again.'
end
end
end
end
a = CommandLine.new('new_accounts.txt')
a.run
Let's say I want the user to enter '-a tommy likes apples' in the command line, I want it to output:
tommy likes apples
The same user tommy could also input '-a tommy likes oranges' which would then update his previous preference:
tommy likes oranges
Any help/direction is appreciated, thanks!
I don't see a problem with using a text file if you are doing something simple. Alternatives are many and without more detail I'm afraid I can't make a good recommendation.
def add_user(input)
File.open('new_accounts.txt', 'w') {|file|
file.write(input)
}
puts input
end
FYI: This will make it so that your text file updates. :-)
EDIT: Changed the add_user method.

Resources