Daniel's Blog

Interesting parts of Ruby

I recently took an introductory course on Ruby, and here are some interesting things I noticed.

Everything is an object.

And objects can be modified. For example,

class Integer
  def squared
    self ** 2
  end
end

puts 3.squared
## 9

Concise and readable code

Ruby is designed for "productivity and fun"- some elegant lines I noticed:

Printing out each element of an array:

[1, 2, 3, 4, 5].each { |elem| puts elem }

Unless operator:

# Let someone in, unless they are banned from our pub.
def openPubDoor()
	"Door Opened!" unless bannedUsers.include? user
end
# Add an item to a users basket, unless the basked already contains the maxQuantity of that item
def addToBasket()
	basket.append(item) unless basket.count(item) >= maxQuantity
end

Unopinionated nature

There are many approaches to the same task in Ruby. This can be good or bad.

I find it can be difficult to be consistent when there are many ways of doing the same thing, which can make reading code confusing.