Tag Archives: Ruby

Quick Tip: Setting Variables Inside Array & Hash Literals

Did you know that you can assign variables inside Ruby’s array and hash literals?

While the values used inside square bracket array literals are typically hard-coded, provided by a variable, computed from an inline expression or generated by a method, any valid Ruby statement can be used. The same is true for both keys and values used in hash literal key => value pairs. Continue reading

RSpec: be true & be_true Are Different!

, , ,

RSpec’s be true and be_true look deceptively similar. In fact, their naming suggests that they might be synonyms for the same assertion. Can the two clauses be used interchangeably to produce the same effect? No!

Both check trueness but from different perspectives. be true checks whether the compared-against value is true: “Does the value literally equal true?” be_true asserts that the test value evaluates to true: “Is the value truthy?” be false and be_false are the respective inverse match clauses. Continue reading

Let It Quack!

, ,

Duck Crossing Warning SignAn entire day passed. The repugnant lines sat festering. Finally, their odious stench wafted strong enough to give me a start. What had I done?!

The situation started simply enough. I realized several kinds of transactions shared common logic. Despising duplication as a good programmer should, I placed this shared behavior in a base class which the various kinds of transactions would subclass. Continue reading

Ruby: Case Testing Against Arrays of Values

,

Did you know that a when clause in a Ruby case statement can test against each item in an array? If any item in the array matches the case statement’s comparison (target) value, the when clause will evaluate to true.

In the below example, :express_truck will be returned if country matches any of the truckable_countries.

truckable_countries = ['United States', 'Canada', 'Mexico']

ship_via = case country
           when *truckable_countries
           	:express_truck
           else
           	:supersonic_jet
           end

Continue reading