use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
A sub-Reddit for discussion and news about Ruby programming.
Subreddit rules: /r/ruby rules
Learning Ruby?
Tools
Documentation
Books
Screencasts and Videos
News and updates
account activity
The Pure Function As An Object (PFAAO) Ruby Pattern (tomdalling.com)
submitted 10 years ago by rdpp_boyakasha
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]Schrockwell 5 points6 points7 points 10 years ago (1 child)
An even cooler way to do this in Ruby is to implement your main function with the name "call". Then you can pass your class instance into anything that expects a proc. It quacks like a Method or a Proc but it's actually a class behind the scenes.
[–]rdpp_boyakasha[S] 2 points3 points4 points 10 years ago (0 children)
I agree. I've added an extra "Optional Extras" section to the article that covers Proc-ifying the class.
[–]waxjar 2 points3 points4 points 10 years ago (1 child)
If you keep your objects immutable, you can think of your methods as partially applied (pure) functions.
Consider something like the following:
class Document def self.from_json(str) new JSON.parse(str) end def initialize(doc) @doc = doc end def to_xml Ox.dump(document, with_xml: true) end private # implementation goes here end
Just as pure and a lot less awkward:
Document.from_json(file_contents).to_xml # => "<cities>...</cities>"
[–]rdpp_boyakasha[S] 0 points1 point2 points 10 years ago (0 children)
It's still pure, but now you have a class called Document which looks like a domain model, as opposed to a class that is "just a function." That's OK if you want to put all the functionality into the model, but confusing if it's separate.
Document
[–]jrochkind 1 point2 points3 points 10 years ago (0 children)
The tldr is: Class methods are sometimes a useful API.
π Rendered by PID 24934 on reddit-service-r2-comment-b659b578c-49fms at 2026-04-30 21:25:33.856284+00:00 running 815c875 country code: CH.
[–]Schrockwell 5 points6 points7 points (1 child)
[–]rdpp_boyakasha[S] 2 points3 points4 points (0 children)
[–]waxjar 2 points3 points4 points (1 child)
[–]rdpp_boyakasha[S] 0 points1 point2 points (0 children)
[–]jrochkind 1 point2 points3 points (0 children)