Home > Back-end >  Ruby puts command creates a new line in bash
Ruby puts command creates a new line in bash

Time:12-16

When I put the final puts command in the code :

#!/usr/bin/env ruby
#Este comando cita sua idade e nome
puts "digite sua idade:"
idade = gets.to_i
puts "digite seu nome:"
nome = gets
puts "Olá #{nome}! você nasceu em #{2021-idade}"

and run it on bash, it creates a new line inside the line. how to make it to be just one line?

bash image

CodePudding user response:

The print method will continue to output on the same line.

puts will always add a new line.

There is a great reference here: https://flexiple.com/puts-vs-p-vs-print-ruby/

You can also always check the documentation:

puts - https://www.rubydoc.info/stdlib/core/IO:puts "Note that puts always uses newlines"

print- https://www.rubydoc.info/stdlib/core/IO:print

If you are worried about the input having a new line, check out gets.chomp

https://www.rubyguides.com/2019/10/ruby-chomp-gets/

puts "digite sua idade:"
idade = gets.to_i
puts "digite seu nome:"
nome = gets.chomp #<- add .chomp here to remove \n from input
puts "Olá #{nome}! você nasceu em #{2021-idade}"

CodePudding user response:

I'm assuming there's a typo in your code, and it's supposed to be:

#!/usr/bin/env ruby
#Este comando cita sua idade e nome
puts "digite sua idade:"
idade = gets.to_i
puts "digite seu nome:"
nome = gets
puts "Olá #{nome}! você nasceu em #{2021-idade}"

The newline appears after the name because gets includes the newline character, which you then interpolate into the string you're printing. You can use #chomp or #strip to remove the newine (and potentially any unwanted whitespace around the input. You can see this by calling these in irb.

irb(main):003:0> gets
hello
=> "hello\n"
irb(main):004:0> gets.chomp
hello
=> "hello"
irb(main):005:0> gets.strip
  hello
=> "hello"
irb(main):006:0>
  •  Tags:  
  • ruby
  • Related