What is the difference between print and puts?
puts
adds a new line to the end of each argument if there is not one already.
print
does not add a new line.
For example:
puts [[1,2,3], [4,5,nil]]
Would return:
1
2
3
4
5
Whereas print [[1,2,3], [4,5,nil]]
would return:
[[1,2,3], [4,5,nil]]
Notice how puts does not output the nil value whereas print does.
What is the differences between print and puts in Ruby with example?
irb(main):014:0> class Person
irb(main):015:1> attr_accessor :name, :age, :gender
irb(main):016:1> end
=> nil
irb(main):017:0> person = Person.new
=> #<Person:0x2bf03e0>
irb(main):018:0> person.name = "Robert"
=> "Robert"
irb(main):019:0> person.age = 52
=> 52
irb(main):020:0> person.gender = "male"
=> "male"
irb(main):021:0> puts person
#<Person:0x2bf03e0>
=> nil
irb(main):022:0> print person
#<Person:0x2bf03e0>=> nil
irb(main):023:0> print person.name
Robert=> nil
irb(main):024:0> puts person.name
Robert
=> nil
The difference between print and puts is that puts automatically moves the output cursor to the next line (that is, it adds a newline character to start a new line unless the string already ends with a newline), whereas print continues printing text onto the same line as the previous time.
puts isn't prefixed by the name of a class or object upon which to complete the method and puts is a method made available from the Kernel module and that is included and searched by default, so usually you won’t need to use Kernel.puts to refer to it.
Kernel.puts "Hello, world!"
puts takes only one argument and is rarely followed by other methods or logic, so parentheses are not strictly necessary.
Difference between print, put and say?
put $a
is like print $a.Str ~ “\n”
say $a
is like print $a.gist ~ “\n”
put
is more computer readable.say
is more human readable.
put 1 .. 8 # 1 2 3 4 5 6 7 8
say 1 .. 8 # 1..8
Learn more about .gist
here.
———
More accurately, put
and say
append the value of the nl-out
attribute of the output filehandle, which by default is \n
. You can override it, though. Thanks Brad Gilbert for pointing that out.
What is the difference between printf() and puts() in C?
puts
is simpler than printf
but be aware that the former automatically appends a newline. If that's not what you want, you can fputs
your string to stdout or use printf
.
p vs puts in Ruby
p foo
prints foo.inspect
followed by a newline, i.e. it prints the value of inspect
instead of to_s
, which is more suitable for debugging (because you can e.g. tell the difference between 1
, "1"
and "2\b1"
, which you can't when printing without inspect
).
Difference between puts() and printf() in C while using sleep()
This is because of buffering - by default, standard out buffers up to each new line. printf()
does not include a newline, so output isn't flushed. puts()
includes a newline, so output is flushed.
You can cause printf()
to flush by putting a newline:
printf("hello, world\n");
or by calling fflush()
directly:
fflush(stdout);
For more about buffering, see the man page for setbuf()
:
The three types of buffering available are unbuffered, block buffered, and
line buffered. When an output stream is unbuffered, information appears on
the destination file or terminal as soon as written; when it is block
buffered many characters are saved up and written as a block; when it
is line buffered characters are saved up until a newline is output or input
is read from any stream attached to a terminal device (typically stdin).
....
If a stream refers to a terminal (as stdout normally does) it is
line buffered.
....
The standard error stream stderr is always unbuffered by default.
difference between fputs and puts in c
puts
appends a newline to the string, and fputs
doesn't.
Otherwise there is no difference, except of course that with fputs
you can specify a different stream, while puts
always writes to stdout
.
What's the difference between `puts` and `return` result?
Expression
In most languages, return
in a method means giving a value to the caller.
In Ruby, everything is an expression. In an essence, the last line of a method is automatically called with return
. As an example, the following methods are equivalent:
def bark_a
'Woof!'
end
def bark_b
return 'Woof!'
end
However, some methods may not be return
ing anything.
def bark_c
end
In this case, ruby is actually returning a nil
object. An example would be the
puts
method. The puts
method simply displays whatever you've given it.
So in your example,
def bark
puts "Loud Bark"
end
is actually doing 2 things.
- It's calling the
puts
method (displayingLoud Bark
to the terminal screen) - then it's giving a
nil
value back to the method caller.
You can try running puts nil
and see what's printed out!
"#{}"
Calling #{}
in ruby is called interpolation, which is basically putting the variables together in their closest string
representation value. The following statements are roughly equivalent:
puts "One plus one equals #{1 + 1}"
puts "One plus one equals " + (1 + 1).to_s
Your example
With all the information above, we can now go through your example step-by-step.
The line puts "#{max.name} goes #{max.bark}"
can be separated into a few steps
- Calls the
name
method - The value
return
ed is converted into the closeststring
representation (In this case we don't need to do anything sincename
is already astring
) - The value is then saved to a temporary variable
At this point, our temporary variable is Max goes
.
- Calls the
bark
method - The line
puts "Loud Bark"
gets executed since we're calling it in thebark
method. - Terminal(console) displays "Loud Bark"
- Since the
puts
method returns anil
value, thebark
method is also going toreturn
anil
value because it's the last line of thebark
method. (Read "Expression" above) nil
is then converted to the closeststring
representation (which is "")- It is then saved to a temporary variable
The temporary variable is now Max goes
Now, the temporary variable is passed into the
puts
method, and the terminal(console) displays "Max goes "Program finishes
Therefore, your example prints out
Loud Bark
Max goes
However, if we change the puts
inside the bark
method to return
,
Step 6 will not happen.
Instead of return
ing a nil
value in step 7, it will return
"Load bark"
Step 8 will not happen since "Loud bark"
already a string
value
and the temporary value after step 9 will become Max goes Loud bark
Hope this helps!
Difference between print and return
return
ends current method returning passed parameter as a result. Example:
def add(a, b)
return a + b
end
c = add(1, 2)
In Ruby last statement returns value automatically. So we can define our add
method like this
def add(a, b)
a + b
end
But return
is very useful, if you want to end a method execution prior to the last line. For example:
def specialAdd(a, b)
if a < 0
return -1
end
a + b
end
This method returns always -1 if the first argument is negative. In all other cases it works just like add
method.
On the other hand the print
method outputs the passed parameter to the standard output (console) returning nil
as a result. We can see it using irb
- interactive ruby console:
$ irb
irb(main):002:0> print "Hello World\n"
Hello World
=> nil
irb(main):003:0>
Here we see "Hello World"
plus newline printed. The returned value of the print method is nil
.
Related Topics
Ruby - Access Multidimensional Hash and Avoid Access Nil Object
Uninstalling All Gems Ruby 2.0.0
Correctly Doing Redirect_To :Back in Ruby on Rails When Referrer Is Not Available
How to Use Bundler Behind a Proxy
Rails: an Elegant Way to Display a Message When There Are No Elements in Database
How to Use Rvm and Create Globally Available Gems
What Is the Use of Gemfile in Rails
How to Search a Folder and All of Its Subfolders For Files of a Certain Type
How to Fix "Your Ruby Version Is 2.3.0, But Your Gemfile Specified 2.2.5" While Server Starting
Rails Respond_To Format.Js API
Get Current Stack Trace in Ruby Without Raising an Exception
How to Save a Base64 String as an Image Using Ruby
How to Use Global Variables or Constant Values in Ruby
Getting Fields_For and Accepts_Nested_Attributes_For to Work With a Belongs_To Relationship