Reputation: 65
My code is this:
require 'date'
class Account
attr_reader :date, :balance
def initialize
@balance = 0
@date = DateTime.now.strftime "%d/%m/%Y"
@transaction = ["date || credit || debit || balance", "#{@date} || #{@credit} || #{@debit} || #{@balance}"]
end
def statement
return @transaction.join("\n")
end
end
I want to call account = Account.new
and then account.statement
to produce a line break between the two statements in the @transaction
array.
The code prints "\n"
as is instead of converting to a line break. It works if I use puts
instead of return
, but I need to use return
in order for my RSpec tests to work.
Any help would be appreciated.
Upvotes: 0
Views: 2828
Reputation: 28305
When you run code in the console (e.g. irb
or pry
), you see the inspected response of each line/method that gets executed.
For example, try the following:
> puts "hello\nworld"
hello
world
> "hello\nworld"
=> "hello\nworld"
> puts "hello\nworld".inspect
"hello\nworld"
This behaviour is an intentional, valuable feature of the console. It allows you to easy distinguish between different types of whitespace (tabs, spaces, newlines, carriage returns, ...); it allows you to distinguish between variable types (strings vs integers etc); it allows you to see non-printed characters, such as non-breaking space; and so on.
Your code above works fine. The \n
is a new line character.
The only "issue" is that you are seeing it displayed in its escaped form (\n
) in the console.
If you print the response in the console, you will see the newline displayed in its normal way:
> account = Account.new
> puts account.statement
Upvotes: 2