My survival kit of Ruby basic methods

Introduction

The methods every Ruby beginner should know

  • This article is my personal answer to the following question: how many Ruby methods do we need to know to be fluent enough in Ruby?
  • This question is difficult to answer, especially for beginners, with no experience at all in coding, which is my case. I guess it is very similar to asking how many words should we know to be fluent in a foreign language. An instinctive answer would be the more words we know, the better we can express ourselves.
  • However, I do feel there is a limited number of useful methods that can be part of a survival kit.

How to learn and review new methods?

  • There are basically 2 ways of learning and reviewing methods:
    1. You can learn and review methods related to specific objects/Classes. For example: you can list all the methods you know that can be called on Strings.
    2. You can learn and review methods that do similar things. This implies regrouping methods by themes. For example, you can list the methods you know that can permanently delete elements in a collection.
  • The 1st way is quite standardized, it is how methods are presented in the Ruby documentation. The 2nd way is more difficult to come with because you have to find relevant themes and you have to associate methods with action verbs.
  • My survival kit shows how I personnaly regrouped similar methods together. This helped me a lot in gaining fluency with methods and writing more precise pseudo-code.
  • I sytematically separated mutating methods from non-mutating methods. Beware of mutating methods. In particular, It's important to pay attention to what they return. They do not always return the mutated object.

The methods seen in Launch School

  • One of Launch School's most enjoyable feature is the amount of exercises available to practice.
  • I listed 336 exercices through sections 100 and 101. They either appear as pratical exercices in the Courses section, or in the dedicated Exercises section. I did not count the exercises of the book Introduction to Programming with Ruby.
  • I listed 5 methods that appear in a Lesson without appearing in an exercice: Array#[]= (Quite surprising not to see this method in any exercise, I might have missed it), Object#dup, Object#clone, Object#frozen? and Object#freeze.
  • Each exercise presents one or several methods in the Problem section, in the Solution section or in the Further Exploration section. I listed all of these.
  • This got me to a solid list of 196 unique methods seen in Launch School. You can download the full list below.

Building my survival kit of methods

  • From Launch School's 196 unique methods, I excluded 21 methods that were either too specific or difficult to use at an early stage (Regex necessary).
  • I also added 62 complementary methods, that are really close to the ones that were already in the list. For example, the methods for Floats, the destructive version of String#strip.
  • This got me to 237 unique methods.

The 5 basic objects

  • Most of the methods listed below are related to the 5 following basic objects:
    1. Numbers (Integers and Floats)
    2. Strings
    3. Arrays
    4. Hashes
    5. Ranges
  • Numbers in Ruby are immutable objects. There are no methods that can mutate numbers. We often use 2 classes to deal with numbers in Ruby : The Integer Class and the Float Class. I also included some methods from the Rational Class.
  • Strings and Arrays are index-based collections, starting at index 0. The last index is the size of the object minus 1.
  • Arrays, Hashes and Ranges are Enumerable collections. Their classes define a #each method. Methods of the Enumerable module can be called on objects of these classes.
  • Unlike Arrays, Hashes and Ranges, Strings are collections that can only contain the same type of objects, characters, which are individual Strings.
  • Numbers, Strings and Arrays are Comparable objects. They can be compared to the same type of objects by using the <= data-preserve-html-node="true"> method.

My survival kit

1. The methods to print and format outputs

1 Kernel#print
Kernel#puts
Kernel#p
2 String#ljust
String#center
String#rjust
3 Kernel#format
4 Object#inspect
  • Kernel#print, Kernel#p and Kernel#puts are all printing methods, but Kernel#p prints object.inspect while Kernel#puts prints object.to_s.
  • Kernel#format is quite complex to use but here are some convenient forms to format numbers:
    1. format('%02d', number): to prepend integers with 0 to obtain 2-digit integers
    2. format('%03d', number): to prepend integers with 0 to obtain 3-digit integers
    3. format('%.2f', number): to have floats with 2 decimals
    4. format('%.3f', number): to have floats with 3 decimals

2. The method to read inputs

1 Kernel#gets

3. The methods to calculate and count

Adding Integer#+
Float#+
Rational#+
Enumerable#sum, Array#sum
Substracting Integer#-
Float#-
Rational#-
Multiplying Integer#*
Float#*
Integer#**
Float#**
Dividing Integer#/
Float#/
Integer#%
Float#%
Numeric#divmod
Numeric#remainder
Numeric#fdiv
Counting the number of specific elements in a collection (Argument necessary) String#count
Enumerable#count, Array#count
Counting the total number of elements in a collection String#length or String#size
Array#length or Array#size
Range#size
Hash#size
Enumerable#count, Array#count
Rounding a Float Float#round
Float#ceil
Choosing a random number Kernel#rand
Combining elements of a collection by applying a binary operation Enumerable#inject or Enumerable#reduce

4. The methods to compare objects

Integer Integer#<=>
Integer#<
Integer#<=
Integer#>
Integer#>=
Integer#==
Integer#even?
Integer#odd?
Comparable#between?
Float Float#<=>
Float#<
Float#<=
Float#>
Float#>=
Float#==
Comparable#between?
Integer, Float or Rational Numeric#nonzero?
Numeric#zero?
String String#<=>
String#==
String#casecmp
Comparable#between?
Array Array#<=>
Array#==
Range Range#==
Range#cover?
Hash Hash#==

5. The methods to have more information about objects

1 Object#object_id
2 Object#frozen?

6. The methods to create new objects

1 String::new
2 Array::new
3 Hash::new
  • Even though it is more common to use Ruby's literals to create new objects, the Class methods can be quite helpful to set default values for Arrays and Hashes.

7. The methods to iterate

1 Kernel#loop
2 Integer#times
Integer#upto
Integer#downto
3 String#each_char
4 Enumerable#each, Array#each, Hash#each, Range#each
5 Enumerable#reverse_each, Array#reverse_each
6 Enumerable#each_with_index
7 Enumerable#each_with_object
8 Hash#each_pair
Hash#each_key
Hash#each_value

8. The methods to find a specific element in a collection

Finding the index of the first occurence of a substring String#index
Finding the index of the first occurence of an element in Enumerable collections (Array, Hash, Range) Enumerable#find_index, Array#find_index
Array#index
Finding the key of a specific value in a Hash Hash#key
Finding the first occurence of an element in Enumerable collections (Array, Hash, Range) based on condition(s) Enumerable#find or Enumerable#detect

9. The methods to add or replace elements in a collection - Non-mutating methods

1 String#gsub

10. The methods to add or replace elements in a collection - Mutating methods

Adding at the end (Appending) String#<<
Array#<<
Array#push
Adding at the beginning (Prepending) String#prepend
Array#unshift
Adding or replacing elements String#[]=
String#gsub!
Array#[]=
Hash#[]=
Adding elements String#insert
Array#insert
  • Be careful with the method String#gsub!. If nothing is replaced, the method returns nil, which is not the case for String#gsub.

11. The methods to check a condition in Enumerable collections (Array, Hash, Range)

Does the Array or Range include...? Enumerable#include? or Enumerable#member?, Array#include?, Range#include?, Range#member?
Does the Hash has a specific key? Enumerable#include? or Enumerable#member?, Hash#include?, Hash#member?
Hash#key?
Hash#has_key?
Does the Hash has a specific value? Hash#value?
Hash#has_value?
Is the collection empty? Array#empty?
Hash#empty?
Do all elements of the collection verify the block's condition? Enumerable#all?, Array#all?
Do all elements of the collection do not verify the block's condition? Enumerable#none?, Array#none?
Does any element of the object verify the block's condition? Enumerable#any?, Array#any?, Hash#any?

12. The methods to check a condition in Strings

Does the String include...? String#include?
Is the String empty? String#empty?
Does the String start with...? String#start_with?
Does the string end with...? String#end_with?
Does the string match another string? String#=~
String#match?

13. The methods to select/delete - Non-mutating methods

Selecting 1 or several character(s) or element(s) based on indexes or keys String#[] or String#slice
Array#[] or Array#slice
Array#fetch
Hash#[]
Hash#fetch
Selecting 1 or several element(s) of an Enumerable collection (Array, Hash, Range) Enumerable#select, Array#select, Hash#select
Enumerable#reject, Array#reject, Hash#reject
Selecting 1 or several specific element(s) of a Hash Hash#keys
Hash#values
Hash#assoc
Selecting the first character or the first element(s) String#chr
Enumerable#first, Array#first, Range#first
Enumerable#take, Array#take
Selecting the last element(s) Array#last
Range#last
Deleting the last character(s) String#chop
String#chomp
Selecting the lowest value(s) of an Enumerable collection (Array, Hash, Range) Enumerable#min, Array#min, Range#min
Enumerable#min_by
Selecting the highest value(s) of an Enumerable collection (Array, Hash, Range) Enumerable#max, Array#max, Range#max
Enumerable#max_by
Selecting 1 or several random element(s) of an Array Array#sample
Deleting all occurences of character(s) String#delete
Deleting duplicates Array#uniq
Deleting duplicated consecutive characters String#squeeze

14. The methods to select/delete - Mutating methods

Selecting/Deleting characters/elements based on indexes or key String#slice!
Array#slice!
Array#delete_at
Hash#delete
Selecting/Deleting element(s) based on condition(s) Array#select!
Array#keep_if
Array#reject!
Array#delete_if
Hash#select!
Hash#keep_if
Hash#reject!
Hash#delete_if
Deleting all occurences of character(s) or element String#delete!
Array#delete
Deleting duplicates Array#uniq!
Deleting duplicated consecutive characters String#squeeze!
Deleting the first element
Array#shift
Hash#shift
Deleting the last character or element
String#chop!
String#chomp!
Array#pop

15. The methods to concatenate 2 collections - Non-mutating methods

Strings String#+
String#*
Arrays Array#+
Array#*

16. The methods to concatenate 2 collections - Mutating methods

1 String#concat
2 Array#concat

17. The methods to reorder collections - Non-mutating methods

1 String#reverse
2 Array#reverse
3 Array#shuffle

18. The methods to reorder collections - Mutating methods

1 String#reverse!
2 Array#reverse!
3 Array#shuffle!

19. The methods to transform collections - Non-mutating methods

1 String#capitalize
String#downcase
String#upcase
String#swapcase
String#capitalize
String#strip
2 Enumerable#map, Array#map
3
Array#flatten
Hash#flatten

20. The methods to transform collections - Mutating methods

1 String#downcase!
String#upcase!
String#swapcase!
String#capitalize!
String#strip!
2 Array#map!
3 Array#flatten!

21. The methods to sort the elements of a collection - Non-mutating methods

Sorting an Enumerable collection (Array, Hash, Range)
Enumerable#sort, Array#sort
Enumerable#sort_by
Enumerable#partition

22. The methods to sort the elements of a collection - Mutating methods

1 Array#sort!
2 Array#sort_by!

23. The methods to convert objects

Converting into an Integer String#to_i
Float#to_i
Converting into a Float String#to_f
Integer#to_f
Converting into a String Array#join
Integer#to_s
Float#to_s
Converting into an Array
String#chars
String#split
Hash#to_a
Range#to_a
Converting into a Hash Array#to_h
Converting into a Symbol String#to_sym

24. The methods to merge 2 collections - Non-mutating methods

1 Array#|
2 Hash#merge

25. The methods to merge 2 collections - Mutating methods

1 Hash#merge!

26. The methods to copy and freeze objects

1 Object#dup
Object#clone
2 Object#freeze
  • Object#dup and Object#clone are both shallow copying methods, but Object#clone preserves the frozen state of the object whereas Object#dup does not.

Initial publication date: 2019-08-07
Last updated: 2019-08-20