Ruby Quick Reference
Updated: 2021-03-09
Published: 2017-10-02
Comment
ruby
# Single line comment
# Multiple
# line
# commentVariable
ruby
stuff = "stuff"String
Stings are mutable in Ruby
ruby
"Single line string"HERE Doc
HERE are used for multi-line strings
ruby
# Old style - Ruby < 2.3 keep white space preceding string.
stuff = <<-DOC
Stuff and thing.
More stuff and things
DOC
#=> " Stuff and thing.\n More stuff and things\n"
# Squiggly line style - Ruby >= 2.3 strips preceding white space
stuff = <<~DOC
Stuff and thing.
More stuff and things
DOC
#=> "Stuff and thing.\nMore stuff and things\n"Symbol
Symbols are similar to strings except they are immutable
ruby
:stuffInteger
ruby
42Boolean
ruby
true
# or
falseArray
ruby
["stuff", "things"]Hash
ruby
# Old syntax - Ruby < 1.9
{:stuff_key => "stuff_value", :things_key => "things_value"}
# New syntax - Ruby >= 1.9
{stuff_key: "stuff_value", things_key: "things_value"}For Loop
ruby
# Iterate array with a block
things.each do |thing|
puts "#{thing}"
end
# One line block syntax for short code blocks
things.each {|thing| puts "#{thing}"}
# Iterate hash
stuff.each do |key, value|
puts "#{key} #{value}"
endWhile Loop
ruby
i = 1
while i < 42 do
puts(i)
i += 1
endIf, Elsif, Else
ruby
if 1 > 42
puts "One"
elsif 42 < 1
puts "The answer"
else
puts "Maths is fun"
endFunction
ruby
def stuff
# The last element in a function is returned automatically
["stuff", "more stuff", "other stuff"]
endClass
ruby
class StuffAndThings
attr_reader :stuff # Getter only
attr_writer :things # Setter only
attr_accessor :blah # Getter and Setter
def initialize(stuff, things, blah)
@stuff = stuff
@things = things
@blah = blah
end
endTags
#ruby