How to do a newline in output - ruby

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"

Related

Why does the Ruby file have a NoMethodError?

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.

Chat like over line output of puts

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

How to read a file after it's been written to in Ruby

When I run the following code taken from the Learn Ruby the Hard Way Course Exercise 16,
filename = ARGV.first
target = open(filename, 'w+')
puts "Now I'm going to ask you for three lines."
print "line 1: "
line1 = $stdin.gets.chomp
print "line 2: "
line2 = $stdin.gets.chomp
print "line 3: "
line3 = $stdin.gets.chomp
puts "I'm going to write these to the file."
target.write(line1 + "\n" + line2 + "\n" + line3)
puts "And now I'm going to print the file to prove I have altered it."
puts target.read
puts "And finally, we close it."
target.close
the line puts target.read does not print the three input lines, even though the text file does change.
I have tried changing the mode used by the open method and adding a new open method before calling the read method. Creating a separate program with the same script to read and print text file works as expected.
How can I read a file I have just written to? Why does it not work when I write and read within the same program?
why does it not work when I write and read within the same program
The answer is that when you write to a file, your IO stream is set to the end of where you have written. When you read, it continues from this point. In this case, after writing, you have reached the end of the file and there is nothing else to 'read'. You can use IO#rewind to reroll to the beginning and print out what was just written to through the IO Stream.
filename = 'Test.txt'
target = open(filename, 'w+')
text = '12345'
target.write(text) # target points to EOF
# Note that if you print target.write(), it will tell you the 'index' of where the IO stream is pointing. In this case 5 characters into the file.
puts "And now I'm going to rewind the file"
puts target.rewind # go back to the beginning of the file.
# => 0
puts "And now I'm going to print the file to prove I have rewound it."
puts target.read # read the file, target now points to EOF.
# => '12345'
target.close
File.open("my/file/path", "r") do |f|
f.each_line do |line|
puts line
end
end
File is closed automatically at end of block
It is also possible to explicitly close file after as above (pass a block to open closes it for you):
f = File.open("my/file/path", "r")
f.each_line do |line|
puts line
end
f.close
Credit to: https://stackoverflow.com/a/5545284/8328756

Passing line from file as argument to puts?

is it possible to do something like this?
File.open('/etc/logo', 'r') do |f|
f.each_line{ |line| puts line }
end
But I don't want the content of lines to be printed as text but rather figured out as arguments to the puts command. To make myself clear, this is the example /etc/logo:
"\e[34m" + 'BLUE COLOR' + "\e[31m" + 'RED COLOR'
I want to separate the ASCII logo from my code. Thank you for your ideas.
File.open('/etc/logo', 'r') do |f|
f.each_line{ |line| eval "puts #{line}" }
end
Don't let anyone edit that file.
If you want a more secure way to do it, try this:
File.open('/etc/logo', 'r') do |f|
f.each_line{ |line|
puts line.gsub(/\\e/, "\e")
}
end
For this, you should use a file like:
\e[34mBLUE COLOR\e[31mRED COLOR
This just replaces the escaped \e with the real character.

Concatenating strings with variables with Ruby

I am writing a test script that opens a file with a list of URLs without the "www" and "com".
I am trying to read each line and put the line into the URL. I then check to see if it redirects or even exists.
My problem is when I read the line from the file and assign it to a variable. I then do a compare with what's in the URL after loading and what I initially put in there, but it seems to be adding a return after my variable.
Basically it is always saying redirect because it puts "http://www.line\n.com/".
How can I get rid of the "\n"?
counter = 1
file = File.new("Data/activeSites.txt", "r")
while (line = file.gets)
puts "#{counter}: #{line}"
counter = counter + 1
browser.goto("http://www." + line + ".com/")
if browser.url == "http://www." + line + ".com/"
puts "Did not redirect"
else
puts ("Redirected to " + browser.url)
#puts ("http://www." + line + ".com/")
puts "http://www.#{line}.com/"
end
Basically it is always saying redirect because it puts http://www.line and then return .com/
How can I get rid of the return?
Short answer: strip
"text\n ".strip # => "text"
Long answer:
Your code isn't very ruby-like and could be refactored.
# Using File#each_line, the line will not include the newline character
# Adding with_index will add the current line index as a parameter to the block
File.open("Data/activeSites.txt").each_line.with_index do |line, counter|
puts "#{counter + 1}: #{line}"
# You're using this 3 times already, let's make it a variable
url = "http://#{line}.com"
browser.goto(url)
if browser.url == url
puts "Did not redirect"
else
puts ("Redirected to " + browser.url)
puts url
end
end
That's because your lines are terminated by a newline. You need to strip it off:
while (line = file.gets)
line.strip!
puts "#{counter}: #{line}"
# ...
Note that there are better ways of iterating over the lines in a file:
File.foreach("Data/activeSites.txt") do |line|
# ...
end
This is your code after reindenting it to the "Ruby way":
counter = 1
file = File.new("Data/activeSites.txt", "r")
while (line = file.gets)
puts "#{counter}: #{line}"
counter = counter + 1
browser.goto("http://www." + line + ".com/")
if browser.url == "http://www." + line + ".com/"
puts "Did not redirect"
else
puts ("Redirected to " + browser.url)
#puts ("http://www." + line + ".com/")
puts "http://www.#{line}.com/"
end
It's not correct because it's missing a closing end for the while. But, it's also not dealing with file IO correctly.
This is how I'd write it:
File.foreach("Data/activeSites.txt") do |line|
puts "#{ $. }: #{ line }"
browser.goto("http://www.#{ line }.com/")
if browser.url == "http://www.#{ line }.com/"
puts "Did not redirect"
else
puts "Redirected to #{ browser.url }"
puts "http://www.#{ line }.com/"
end
end
File.foreach is a method inherited from IO. If you read the file correctly you don't need to strip or chomp, because Ruby will handle it correctly when IO.foreach reads the line.
Every time IO reads a line it increments the $. global, which is short-hand for $INPUT_LINE_NUMBER. There's no need to keep a counter. Using:
require 'english'
will enable the verbose names. See the English docs for more information.

Resources