This repo is meant to act as a collection of resources describing similar methods, classes, patterns or techniques in Ruby and Rails. These entities might be similar in name, functionality or usage but have some differences that may or may not be readily apparent.
The provided resources largely describe differences in usage and semantics and might not include differences in performance or version compatibility. For more information, including different ways in which items in this list may differ, see the recording from RailsConf 2024 and the slides from the talk.
When reading the resources, consider any accepted answers and discussion and note that some information might be more or less relevant for different versions of Ruby and/or Rails.
This is a work in progress and is not expected to be exhaustive. I do hope, however, it will continue to get closer over time. If you have any suggestions, additions, clarifications or corrections, please feel free to open an issue or a pull request.
NOTE: aliases, such as update and update_attributes from ActiveRecord,
are (largely) not included in this list. There may, however, be differences in
which versions of Ruby or Rails introduced a method and its aliases.
To see a searchable table of contents, click the list button on GitHub visible here:
- Binary Searching and Ruby's bsearch Method by Andrew Vogel
- Effective Use of Array#bsearch by Jemma Issroff
- Fun with flat_map (in Ruby) by Keith Kim
- What Does Ruby's Array#shift do?
- Quick reference for ruby array methods: push/pop vs. shift/unshift by Donna Hogan
- Why Array.new(3, []) works differently than [[], [], []] in Ruby?
- Ruby array creation, Array.new vs []
Array()is shorthand forKernel.Arrayimplicitly
- fetch vs. [] when working with hashes?
- Could someone explain me what is the difference between Hash#dig vs Hash#fetch
- What's the difference between "Hash.new(0)" and "{}"
- A trick with Ruby Hash.new by Fran C.
- Ruby hash default value behavior
- Ruby Hash.new with a block need in-depth explanation
**hashwill give a warning if overwriting an existing keywarning: key :your_key is duplicated and overwritten on line n- what is difference between store vs merge in ruby hashes?
- Merge or reverse_merge a Hash
- Ruby Double Splat Operator: A Comprehensive Cheatsheet by Ilia Kriachkov
- This || That slides by Andy Andrea
- Range#include? vs. Range#cover? by Craig Hafer
Comparisons under this section apply to multiple Enumerable classes.
- each_with_object vs. reduce/inject by Lee Roberts
- 3 Mental Models For Ruby Enumerators by Joël Quenneville
- Understanding Ruby - Enumerable - Iterating and Taking by Brandon Weaver
EnumerabledocsEnumeratordocs
- Single-quoted behavior in heredocs
- Weird Ruby: Single-quoted Heredocs by Bozhidar Batsov
- What's the difference between String.new and a string literal in Ruby?
- Double vs single quotes
#frozen_string_literal: true- Respected by literals and
String() - Not respected by
String.new
- Respected by literals and
- Note: you can also declare single-character strings using the single character literal syntax
chompdocs- Additional complexity over delete_suffix
- Has existed for much longer
delete_suffixdocs- Not introduced until Ruby 2.5
- Heredocs and how to use them in Ruby and Rails by Romil Mehta
- Additional heredoc info
- Weird Ruby: Heredoc Delimiters by Bozhidar Batsov
- fast-ruby
- How do I find if a string starts with another string in Ruby?
- Also consider readability
- What is the difference between tr and gsub? - ruby
- What is the difference between gsub and sub methods for Ruby Strings
- Rounding float in Ruby
- See discussion in accepted answer for distinction
- This || That slides by Andy Andrea
- Using Match vs. =~ in Ruby by Craig Hafer
- Fastest way to check if a string matches a regexp in ruby?
- Module#< docs
- Module#<= docs
- Module#ancestors docs
- More similar to
<=, but see fast-ruby
- More similar to
- Unraveling Classes, Instances and Metaclasses in Ruby by Jeff Kreeftmeijer
- Note: similar to how you can define a class method with
def self.my_method, you can also define a method on an object viadef my_variable.my_methodsimilarly todefine_singleton_method
- Ruby class instance variable vs. class variable
- Difference between class variables and class instance variables?
- Include, Extend, And Prepend In Ruby by Veerpal Brar
- The Difference Between
instance_evalandclass_evalIn Ruby by Emmanuel Hayford - How to understand the difference between class_eval() and instance_eval()?
- Evaluation Options in Ruby by Jay Fields
- Exploring Ruby's Global Constants and Variables by Ariel Juodziukynas
- Some global variables can special meanings in Ruby: link to
docs
- Note that some of these will change over time while your app is running depending on what code gets run (e.g. the regex matching ones), so don't define them manually and expect them to be stable
- Constants are namespaced to the class/module they are defined in; "global"
constants are really nested under
Object- For a list of such constants, you can run
Object.constants
- For a list of such constants, you can run
- Constants can be privatized with
private_constant
- Why you should nest modules in Ruby by Justin Toniazzo
- What is the difference between local, instance, and class variables?
- How do you use global variables or constant values in Ruby?
- Shorthand for instance, class and global variables can be used in String
interpolation, e.g.
"#@foo, world!"instead of"#{@foo}, world!"(link to docs
- Numeric data types in Ruby and when to use them by Rémy Hannequin
FixnumandBignumwere unified underIntegerin Ruby 2.4- However, large integers still differ from smaller integers in terms of object allocation. See Eliminating Intermediate Array Allocations by Aaron Patterson
- How Numbers Work in Ruby: Understanding Integers, Floats & Bigdecimal by Jesus Castello
- This || That slides by Andy Andrea
- Abstract methods and NotImplementedError in Ruby by Nithin Bekal
StructvsOpenStructStructvsData- Ruby 3.2 introduces Data, a new core class for immutable value objects by Alkesh Ghorpade
- Note that differences have changed over time
DateTimedocsActiveSupport::TimeWithZonedocs- See also:
- Meet Fiber, Thread's Cooperative Cousin by Thom Carter
This section includes methods that can be called via syntactic sugar that look like operators.
- What's the difference between equal?, eql?, ===, and ==?
- RSpec matchers
==:eq===:Noneeql?:eqlequal?:equal
- In most cases,
..is used to construct aRange(see "Ranges" section above) - In conditionals (including ternary operators),
..is the flip-flop operator- Flip flop operator in Ruby by Nithin Bekal
- Difference between "or" and || in Ruby?
- The difference in precedence also holds true for
and/&&andnot/!
- Methods (including mathematical operations) are not inherently commutative in Ruby
a + bis equivalent toa.+(b); ifaandbare different classes, a different underlying method will likely be called when swapping the order- Examples
===String === ""vs"" === String/string/ === "string"vs"string" === /string/(1..5) === 3vs3 === (1..5)
*"a" * 3vs3 * "a"
+Time.zone.now + 1.dayvs1.day + Time.zone.now
- What does ||= (or-equals) mean in Ruby?
- These differences also hold for
&&=
- Should I use alias or alias_method?
- A Tale of 3 Aliases by Mateus Pereira
- Ruby, Difference between exec, system and %x() or Backticks
- Note: you can use backticks with a heredoc in order to execute long/multi-line statements. See the docs
- Understanding Ruby - Blocks, Procs, and Lambdas by Brandon Weaver
- Case when docs
- Case in/pattern matching docs
- Of note if you're new to Ruby's pattern matching: "if the value of the
expression does not match any branch of the case expression (and the else
branch is absent), NoMatchingPatternError is raised." In other words, an
elsemay prevent an uncaught exception that you might not expect to be necessary.
- Of note if you're new to Ruby's pattern matching: "if the value of the
expression does not match any branch of the case expression (and the else
branch is absent), NoMatchingPatternError is raised." In other words, an
define_methodis defined onModulewhereasdefine_singleton_methodis defined onObjectdefine_methodis typically used to define an instance method on a class or module whereasdefine_singleton_methodis for defining a method on a single instance of a class
- instance_variable_set can be used to define new instance variables
- local_variable_set cannot be used to define new local variables (except on a specific binding object)
- This || That slides by Andy Andrea
- Recommended approach to monkey patching a class in ruby
- monkey patching vs class_eval?
- Warning: non-HTTPS link: Class_eval vs Define_method by Brian Mehrman
- Ruby's def and instance_eval vs. class_eval
- How to define a private method in Ruby?
- Note the inline option available since Ruby 2.1
- Note that positional privatization does not affect class methods
- Doing a
def self.methodafter aprivatewill not make it a private class method
- Doing a
- What are the differences between "private", "public", and "protected methods"?
- Better Know A Ruby Thing: Methods and Access Control (part 1) by Noel Rappin
- Mastering Refinements in Ruby: A Comprehensive Guide to Safer Monkey Patching: part 1 by Talaat Magdy
- Ruby's redo, retry and next keywords by Thijs Cadier
- About bang methods in Ruby, from its creator
- How to convert a string to lower or upper case in Ruby
- Comment about
downcase!sometimes returningnilis important; don't chain bang method calls
- Comment about
- Both sources are pretty generalizable to bang vs non-bang methods in Ruby
(e.g. not just
downcase/downcase!)
- Throw, Catch, Raise, Rescue – I'm So Confused! by Avdi Grimm
- Why do this Ruby object have both to_s and inspect methods that appear to do the same thing?
- Inspecting Ruby's inspect method by Louis Antonopoulos and Steve Polito
- This || That slides by Andy Andrea
- For Ruby
- For Rails
- Ruby on Rails: length vs size vs count with examples by Gonzalo Galdámez
- This || That slides by Andy Andrea
- Delegating things in Ruby by Paweł Dąbrowski
- Delegate vs Forwardable vs SimpleDelegator — Ruby vs Rails by Lakhveer Singh Rajput
ordercomes from Rails and is used for constructing queries- Method of the Month 1: Ruby's sort vs. sort_by by Brandon Dimcheff
sort.reversevssort_byperformance:
- Faster Rails: How to Check if a Record Exists by Igor Šarčević
- Difference between Action Job/Mailer's
deliver_nowanddeliver_later - What is the difference between deliver & deliver_now in rails?
- Active Record Query Interface
- Rails — find_each v.s find_in_batches v.s in_batches by 涓 / Lynn Chang
- Rendering Collections in Rails by Joël Quenneville
- Rails 4: why is one way of rendering partials so much faster?
- How to Use Flash Messages in Rails by Jesus Castello
- Rails 5: form_for vs form_with
- Rails: form_with vs. form_for vs. form_tag by Scott Espinosa
- Depending on how you use
includes(or alternatives) and the association read method, eitherhas_many :foos, through: :barordelegate :foos, to: :barcould lead to unnecessary extra queries or n+1s - Try to get your team on board with a default so that there are shared patterns to help the team avoid unnecessary queries
- A Visual Guide to Using :includes in Rails by Julianna Roen
- ActiveJob - what's the difference between MyJob.new.perform and MyJob.perform_now?
- Decoding Rails Magic: How Does ActiveJob work? by Karol Galanciak
perform_nowdocsperform_laterdocs
- rails collection_select vs. select
- Extra caveat
-
collection_selectwill do aSELECT *unless you tell it otherwise and will hydrate entire ActiveRecord model objects for each row if you do something like:collection_select(..., ..., Author.all, :id, :name)
-
If you don't already have everything in memory or don't need to reuse the collection, you'll likely get some performance improvements if you instead use
selectlike:select(..., options_for_select(Author.pluck(:name, :id))
-
This does a
SELECT name, idand doesn't build the entire models up in memory. -
As always, do what feels right in the context of your app/team unless you really need every last bit of performance
-
- ActiveRecord's Select & Pluck by Andrew Livingston