Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Object#then method. #11487

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions spec/std/object_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -519,4 +519,24 @@ describe Object do
(x == y).should be_false
end
end

describe "#tap" do
it "yields self" do
"foo".tap { |v| v.should be("foo") }
end

it "always returns self" do
"foo".tap { "bar" }.should be("foo")
end
end

describe "#then" do
it "yields self" do
"foo".then { |v| v.should be("foo") }
end

it "returns yielded block" do
"foo".then { "bar" }.should be("bar")
end
end
end
30 changes: 30 additions & 0 deletions src/object.cr
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,36 @@ class Object
self
end

# Yields `self` to the block and returns the result of the block.
# It’s akin to the pipe operator known from F# and Elixir.
#
# ```
# # Pretty typical code that reads `data.csv` file, parses it and sums one of the columns.
#
# CSV.parse(File.read(File.expand_path("data.csv"), __DIR__))
# .map { |row| row[1].to_i }
# .sum
#
# # Such a code usually takes a few secs to understand.
# # Mainly because we read it left-to-right but it runs right-to-left.
#
# # The same code rewritten using `then`:
#
# "data.csv"
# .then { |name| File.expand_path(name, __DIR__) }
# .then { |path| File.read(path) }
# .then { |body| CSV.parse(body) }
# .map { |row| row[1].to_i }
# .sum
#
# # We can name some benefits:
# # - There’s a clear flow, from top to the bottom
# # - The code is open for additions. Adding more steps to the flow shouldn’t hurt the readability.
# ```
def then
yield self
end

# Yields `self`. `Nil` overrides this method and doesn't yield.
#
# This method is useful for dealing with nilable types, to safely
Expand Down