Using Ruby Metaprogramming to Increase READABILITY of Code

Let’s assume you have a class that has some sort of hash where it stores it’s data. We want to calculate amount that we need to pay, but only if number of items that we want to sell is entered. We’ll also assume that price is already present so we don’t need to check for that. It’s easy:

@store[:total] = @store[:price] * @store[:amount] if @store.has_key?(:amount)

A bit more readable would be:

set_total(price * amount) if amount_exists

(more…)