The Principles of Ruby

Ruby has a few design principles to make programming in the language less stressful and more fun for programmers of other programming languages. These design principles are:

Principle of conciseness: In general, short and concise code is needed to create programs. The initial set of steps to run a program written in English is often referred to as pseudo-code. Ruby is designed so as little additional effort is needed to translate pseudo-code into actual code. Even existing Ruby commands can be made more concise. For example, Ruby’s if statement can be written in three lines or just one.

Principle of consistency: A small set of rules governs the entire language. Sometimes this principle in referred to as the principle of least astonishment or principle of least surprise. In general, if you are familiar with another programming language, the way Ruby behaves should feel intuitive for you. For example, in JavaScript when working with string methods, you can chain them together like so

"alphabet".toUpperCase().concat("Soup")

This JavaScript statement returns “ALPHABETSoup” by first making the string “alphabet” uppercase using the .toUpperCase() method, and then concatenating “soup” to “ALPHABET”. Similarly, the Ruby statement below chains together methods just as you would expect, also returning “ALPHABETSoup”.

"alphabet".upcase.concat("Soup")

Principle of flexibility: There are multiple ways to accomplish the same thing, and even built-in commands can be changed. For example, when writing an if-else statement you can use the words if and else, but you can also accomplish the task with a single “?”. The following code both perform the same task.

Version 1:

if 3>4
puts "the condition is true"
else
puts "the condition is false"
end

Version 2:

puts 3>4 ? "the condition is false" : "the condition is true"

Dummies Insider

Sign up for insider news on books, authors, discounts and more content created just for you.