Search code examples
ruby-on-railsrubygetschomp

changing a variable using gets.chomp()


im trying to write to a file using this code:

  puts "-------------------- TEXT-EDITOR --------------------"
def tor(old_text)
  old_text = gets.chomp #
end


$epic=""

def torr(input)

  tore=  $epic += input + ", "

File.open("tor.txt", "w") do |write|
  write.puts tore
  end
end



loop do
  output = tor(output)
  torr(output)
end

i have read the ultimate guide to ruby programming and it says if i want to make a new line using in the file im writing to using File.open i must use "line one", "line two how can i make this happend using gets.chomp()? try my code and you will see what i mean thank you.


Solution

  • The gets method will bring in any amount of text but it will terminate when you hit 'Enter' (or once the STDIN receives \n). This input record separator is stored in the global variable $/. If you change the input separator in your script, the gets method will actually trade the 'Enter' key for whatever you changed the global variable to.

    $/ = 'EOF' # Or any other string
    lines = gets.chomp
    > This is
    > multilined
    > textEOF
    lines #=> 'This is\nmultilined\ntext'
    

    Enter whatever you want and then type 'EOF' at the end. Once it 'sees' EOF, it'll terminate the gets method. The chomp method will actually strip off the string 'EOF' from the end.

    Then write this to your text file and the \n will translate into new lines.

    File.open('newlines.txt', 'w') {|f| f.puts lines}
    

    newlines.txt:

    This is
    multilined
    text