From 96d4572786a1c41fd9d5f7ddb4602d0cbaeff723 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 19 May 2023 11:51:36 -0500 Subject: [PATCH] Add Return The Thing Being Printed as a Ruby TIL --- README.md | 3 +- ruby/return-the-thing-being-printed.md | 44 ++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 ruby/return-the-thing-being-printed.md diff --git a/README.md b/README.md index 7e749e9..8dc4dcd 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1303 TILs and counting..._ +_1304 TILs and counting..._ --- @@ -1095,6 +1095,7 @@ _1303 TILs and counting..._ - [Require Entire Gemfile In Pry Session](ruby/require-entire-gemfile-in-pry-session.md) - [Rerun Only Failures With RSpec](ruby/rerun-only-failures-with-rspec.md) - [Retry A Block After An Exception](ruby/retry-a-block-after-an-exception.md) +- [Return The Thing Being Printed](ruby/return-the-thing-being-printed.md) - [Returning With Sequel](ruby/returning-with-sequel.md) - [rexml Is A Bundled Gem As Of Ruby 3.0.0](ruby/rexml-is-a-bundled-gem-as-of-ruby-3-0-0.md) - [Run An Older Version Of Bundler](ruby/run-an-older-version-of-bundler.md) diff --git a/ruby/return-the-thing-being-printed.md b/ruby/return-the-thing-being-printed.md new file mode 100644 index 0000000..4e5100e --- /dev/null +++ b/ruby/return-the-thing-being-printed.md @@ -0,0 +1,44 @@ +# Return The Thing Being Printed + +The [`puts`](https://ruby-doc.org/core-3.0.2/Kernel.html#method-i-puts) method +is the canonical way of priting things to stdout in Ruby. Notably, its return +value is always `nil`. Generally this isn't much of an issue, but can be a +potential gotcha while debugging. + +Consider the following method whose behavior you are trying to investigate: + +```ruby +def process(arg) + thing = do_something(arg) + + thing.value +end +``` + +I want to print out the value of thing when I execute the code to see what it +is while debugging. So I add a `puts` statement. + +```ruby +def process(arg) + thing = do_something(arg) + + puts thing.value +end +``` + +Well, I just broke the behavior of `process` because it now returns `nil` +instead of `thing.value`. + +I could add an additional line that returns the correct value. Or I could use +[`p`](https://ruby-doc.org/core-3.0.2/Kernel.html#method-i-p) which both prints +its argument to stdout and returns it as is. + +```ruby +def process(arg) + thing = do_something(arg) + + p thing.value +end +``` + +[source](https://dev.to/lofiandcode/ruby-puts-vs-print-vs-p-vs-pp-vs-awesome-5akl)