Ruby_for_Dragons

An unofficial companion to the DragonRuby documentation

View on GitHub
Home DragonRuby API Documentation Quick Answers Kota’s Cheatsheet Sitemap

Cheatsheet & FAQ

Tips and Tricks to tame the Dragon.

By Pineapple

DragonRuby Starters







For loops still exist, but there’s often better choice

(1..10).each do |i|
  puts i
end

does a thing 10 times

.each is a thing to iterate over an array

a = [3, 6, 8, 4, 5]

a.each do |n|
  puts n
end

and if you need it, a.each_with_index do |n, i| exists as well

but if you just want to do the same operation on the whole array, .map might be more suitable
and if you just want to get the sum of the array, .reduce(:+) will do that as well

My little dragon: arrays are magic

There are some powerful tricks that can be done with arrays (and with anything that’s Enumerable, which includes arrays and hashes)
the trick is trying to understand it all…

a = [3, 6, 8, 4, 5]
puts a.pop      # 5
puts a          # [3, 6, 8, 4]
a.push(7)
puts a          # [3, 6, 8, 4, 7]
puts a.shift    # 3
puts a          # [6, 8, 4, 7]
a.unshift(2)
puts a          # [2, 6, 8, 4, 7]

and i haven’t even started on array maths yet… this example from https://www.ruby-lang.org/en/ still feels incredibly game-changing to me (as primarily a C programmer):

# Ruby knows what you
# mean, even if you
# want to do math on
# an entire Array
cities  = %w[ London
              Oslo
              Paris
              Amsterdam
              Berlin ]
visited = %w[Berlin Oslo]

puts "I still need " +
     "to visit the " +
     "following cities:",
     cities - visited
     
# => I still need to visit the following cities:
# => London
# => Paris
# => Amsterdam

Sometimes, hashes are better

If you don’t need an order, but need paired data values, a hash is probably more suitable

Comparisons to arrays: