im looking for a way to write code above the command line.
Like in chats, where the thing you've typed is displayed above the input line.
For example:
def output(arg1, arg2)
puts arg1 + ":" + arg2
end
puts "-" *30
print "What do you want to say? > "
written_line = gets.chomp
output(username, written_line)
what I want to display, if I type "My Name is Tim" is:
Tim: My Name is Tim
---------------------------------
What do you want to say? > _
Is there an Idea outside how to do it like this?
Thank you
Maybe you are looking for something like this?
def clear_line
print "\e[2K" # Clear entire line
end
def move_up(n)
print "\e[#{n}F" # Move to the beginning of n lines up
end
def positioning_to_output
move_up(2)
clear_line
end
def output(arg1, arg2)
positioning_to_output
puts arg1 + " :" + arg2
clear_line
puts "-" *30
end
username = "Jim Kirk"
4.times do
print "What do you want to say? > "
written_line = gets.chomp
output(username, written_line)
end
Tested on macOS, thanks to escapes sequeces found here
Related
I have a lesson file for an in-terminal tic-tac-toe game. my lib file works when I isolate it. (lib/move.rb)
def display_board(board)
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts "-----------"
puts " #{board[6]} | #{board[7]} | #{board[8]} "
end
def input_to_index(user_input)
index = user_input.to_i - 1
end
def move(arr,ind,char = "X")
arr[ind] = char
end
However, when I run my bin file (bin/move), a NoMethodError shows up referencing the "index = user_input.to_i -1"
#!/usr/bin/env ruby
require_relative '../lib/move.rb'
# Code your CLI Here
puts "Welcome to Tic Tac Toe!"
board = Array.new(9," ")
puts "Where would you like to go?"
input = gets.split
index = input_to_index(input)
input_to_index(input)
move(board,index,"X")
display_board(board)
I don't understand what's wrong and how to fix it.
//#input_to_index is meant to turn the input into an integer, and takes input 1-9 and outputs 0-8
Please help!
split divides string(read from user input, the gets method) into substrings based on a delimiter, returning an array of these substrings. to_i is a method of string that covert it to an integer value, which is not available to an array.
Try to change
gets.split
to
gets
Then the issue will go away.
Couldn't find a better way to write the following:
def get_name
print "Please enter your name: "
name = ""
loop do
break if (name = gets.chomp).match(/^[[:alpha:]]+$/)
print "Please enter your name again (must be one or more letters): "
end
name
end
How can I write this ruby method in a better way?
Problem with your code is that it's trying to do two quite different functions at the same time: validating format and handling user input. Better to separate the two. What do you think of this?
def format_ok?(name)
name =~ /\A[[:alpha:]]+\z/
end
def get_name
print "Please enter your name: "
loop do
name = gets.chomp
return name if format_ok?(name)
print "Please enter your name again (must be one or more letters): "
end
end
Here's another way to write it:
def get_name
print "Please enter your name: "
until gets =~ /^[[:alpha:]]+$/
print "Please enter your name again (must be one or more letters): "
end
$_.chomp
end
It reads a line from standard input until it matches the regular expression, printing an error message otherwise. Upon success, it returns the chomped line (gets assigns to $_).
Just to provide one more variation:
def prompt_name(p)
puts p
gets.chomp.strip
end
def get_name
name = ''
name = prompt_name("Please enter your name #{name.empty? ? '' : 'again '}:") while name !~ /\A[[:alpha:]]+\z/
name
end
how about this?
def get_name
print "Please enter your name: "
name = gets.chomp
until name =~ /[[:alpha:]]/
print "Please enter your name again (must be one or more letters): "
name = gets.chomp
end
puts "your name is #{name}"
end
get_name
> get_name
# Please enter your name: 3212
# Please enter your name again (must be one or more letters): 12Gagan
# your name is 12Gagan
Demo
When coding in Ruby, I came up with an error about needing to state all words the user inputed. I tried to change my code to get it to output that, but the problem remained. Here is my code and the Ruby instructions.
Instructions
Add an if/else statement inside your .each.
if the current word equals the word to be redacted, then print "REDACTED " with that extra space.
Otherwise (else), print word + " ".
The extra space in both cases prevents the words from running together.
puts text = gets.chomp
puts redact = gets.chomp
words = text.split(" ")
words = ['hi', 'hello', 'what', 'why']
words.each do |word|
if gets = words
print "Redact "
else
print word + "Incorrect"
end
end
The problem it says I have with my code is... Oops, try again. Make sure to print each word from the user's text to the console unless that word is the word to be redacted; if it is, print REDACTED (all caps!).
I would appreciate all help, please and thank you.
Ben sorry these guys aren't being too helpful. :D It's been awhile but I hope this helps. In the first section titled "What you'll be building" Codecademy gives you the exact example (the answer) to the final problem in the section. This is always true and may help in the future. What you're looking for:
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 word + " "
else
print "REDACTED "
end
end
Have pass several years I know, but I wanted pass and let my solution for this excercise.
puts "Text to search through: "
text = gets.chomp
puts "Word to redact: "
redact = gets.chomp
words = text.split(',') # "," is necessary to identify each of the words
words.each do |x|
if x == redact # if words repeat, print REDACTED
print "REDACTED"
else # else, only write de word and space
print x + " "
end
end
This is a piece of code:
def add(a, b)
a + b;
end
print "Tell number 1 : "
number1 = gets.to_f
print "and number 2 : "
number2 = gets.to_f
puts "#{number1}+#{number2} = " , add(number1, number2) , "\n"`
When I run it, my results are spread over several lines:
C:\Users\Filip>ruby ext1.rb
Tell number 1 : 2
and number 2 : 3
3.0+3.0 =
5.0
C:\Users\Filip>
Why doesn't puts() print in a single line, and how can keep the output on one line?
gets() includes the newline. Replace it with gets.strip. (Update: You updated your code, so if you're happy working with floats, this is no longer relevant.)
puts() adds a newline for each argument that doesn't already end in a newline. Your code is equivalent to:
print "#{number1}+#{number2} = ", "\n",
add(number1, number2) , "\n",
"\n"
You can replace puts with print:
print "#{number1}+#{number2} = " , add(number1, number2) , "\n"`
or better:
puts "#{number1}+#{number2} = #{add(number1, number2)}"
Because puts prints a string followed by a newline. If you do not want newlines, use print instead.
Puts adds a newline to the end of the output. Print does not. Try print.
http://ruby-doc.org/core-2.0/IO.html#method-i-puts
You might also want to replace gets with gets.chomp.
puts "After entering something, you can see the the 'New Line': "
a = gets
print a
puts "After entering something, you can't see the the 'New Line': "
a = gets.chomp
print a
How do I make \n actually work in my output? At the moment it just writes it all in 1 long block. Thanks for any help
Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
#new = ''
playlist_name = gets.chomp + '.m3u'
music.each do |z|
#new += z + '\n'
end
File.open playlist_name, 'w' do |f|
f.write #new
end
Use "\n" instead of '\n'
I would like to share my experience with \n
I came to notice that "\n" works as-
puts "\n\n" // to provide 2 new lines
but not
p "\n\n"
also
puts '\n\n'
Doesn't works.
Hope will work for you!!
You can do this all in the File.open block:
Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'
File.open playlist_name, 'w' do |f|
music.each do |z|
f.puts z
end
end
Actually you don't even need the block:
Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'
File.open(playlist_name, 'w').puts(music)
For me it didn't work with adding "\n" to the end of an existing argument to puts, so as a workaround I called print on the next line with "\n" as an argument, although I suppose I could have just called puts again.
This did not produce the desired result:
puts "Coach says: #{coach_answer(user_input)}\n"
But this did:
puts "Coach says: #{coach_answer(user_input)}"
print "\n"