4
y = "Ruby\riscool"
x = "Ruby\niscool"

if x == y
  puts x
  puts y
else
  print 'Not equal!'
end

The newline and carriage return character both give the same output. However, the code above is false, and triggers the else statement. I don't understand how I can get the same output, but for both to be unequal? Can someone give and example and explain the difference between the two whitespace characters? Thanks!

Practical1
  • 789
  • 1
  • 8
  • 26
  • 4
    "both give the same output." - no, [they don't](https://pastebin.com/8faQ6fQG). – Sergio Tulentsev Oct 02 '18 at 18:09
  • Look at this [link](https://stackoverflow.com/questions/1761051/difference-between-n-and-r?answertab=active#tab-top) i think its the same in ruby – wehdi Oct 02 '18 at 18:10
  • See also [this answer](https://stackoverflow.com/questions/1552749/difference-between-cr-lf-lf-and-cr-line-break-types). – tadman Oct 02 '18 at 22:29
  • 3
    In most terminals `\r` moves the cursor to the beginning of the line without advancing lines, so you can re-write text. `\n` moves to the beginning *and* advances the line. – tadman Oct 02 '18 at 22:30
  • Just for clarification, is there a difference between the two if I use them in a script and not in a shell? Thanks for the explanation! – Practical1 Oct 02 '18 at 22:36
  • @Practical1: depends on where you'll run that script. In most cases yes, there is a difference. – Sergio Tulentsev Oct 03 '18 at 05:04

1 Answers1

1

\n and \r doesn't make a lot difference in output both are used to print a new line though they perform same action they are different it can be observed in case of input for example if we are getting a matrix as input like:

1 2 3 (\n)

4 5 6 (\n)

7 8 9 (\r)

to give new line as input we will use \n(enter) when the input end carriage return come to play which is (\r).

THUNDER 07
  • 521
  • 5
  • 21