updated: 9th of March 2021
published: 2nd of October 2017
# Single line comment
# Multiple
# line
# comment
stuff = "stuff"
Stings are mutable in Ruby
"Single line string"
HERE are used for multi-line strings
# 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"
Symbols are similar to strings except they are immutable
:stuff
42
true
# or
false
["stuff", "things"]
# 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"}
# 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}"
end
i = 1
while i < 42 do
puts(i)
i += 1
end
if 1 > 42
puts "One"
elsif 42 < 1
puts "The answer"
else
puts "Maths is fun"
end
def stuff
# The last element in a function is returned automatically
["stuff", "more stuff", "other stuff"]
end
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
end