File tree 2 files changed +46
-1
lines changed
2 files changed +46
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
12
12
13
- _ 1303 TILs and counting..._
13
+ _ 1304 TILs and counting..._
14
14
15
15
---
16
16
@@ -1095,6 +1095,7 @@ _1303 TILs and counting..._
1095
1095
- [ Require Entire Gemfile In Pry Session] ( ruby/require-entire-gemfile-in-pry-session.md )
1096
1096
- [ Rerun Only Failures With RSpec] ( ruby/rerun-only-failures-with-rspec.md )
1097
1097
- [ Retry A Block After An Exception] ( ruby/retry-a-block-after-an-exception.md )
1098
+ - [ Return The Thing Being Printed] ( ruby/return-the-thing-being-printed.md )
1098
1099
- [ Returning With Sequel] ( ruby/returning-with-sequel.md )
1099
1100
- [ rexml Is A Bundled Gem As Of Ruby 3.0.0] ( ruby/rexml-is-a-bundled-gem-as-of-ruby-3-0-0.md )
1100
1101
- [ Run An Older Version Of Bundler] ( ruby/run-an-older-version-of-bundler.md )
Original file line number Diff line number Diff line change
1
+ # Return The Thing Being Printed
2
+
3
+ The [ ` puts ` ] ( https://ruby-doc.org/core-3.0.2/Kernel.html#method-i-puts ) method
4
+ is the canonical way of priting things to stdout in Ruby. Notably, its return
5
+ value is always ` nil ` . Generally this isn't much of an issue, but can be a
6
+ potential gotcha while debugging.
7
+
8
+ Consider the following method whose behavior you are trying to investigate:
9
+
10
+ ``` ruby
11
+ def process (arg )
12
+ thing = do_something(arg)
13
+
14
+ thing.value
15
+ end
16
+ ```
17
+
18
+ I want to print out the value of thing when I execute the code to see what it
19
+ is while debugging. So I add a ` puts ` statement.
20
+
21
+ ``` ruby
22
+ def process (arg )
23
+ thing = do_something(arg)
24
+
25
+ puts thing.value
26
+ end
27
+ ```
28
+
29
+ Well, I just broke the behavior of ` process ` because it now returns ` nil `
30
+ instead of ` thing.value ` .
31
+
32
+ I could add an additional line that returns the correct value. Or I could use
33
+ [ ` p ` ] ( https://ruby-doc.org/core-3.0.2/Kernel.html#method-i-p ) which both prints
34
+ its argument to stdout and returns it as is.
35
+
36
+ ``` ruby
37
+ def process (arg )
38
+ thing = do_something(arg)
39
+
40
+ p thing.value
41
+ end
42
+ ```
43
+
44
+ [ source] ( https://dev.to/lofiandcode/ruby-puts-vs-print-vs-p-vs-pp-vs-awesome-5akl )
You can’t perform that action at this time.
0 commit comments