Programming ≈ Fun

Written by Krešimir Bojčić

Small Sample of Ruby Elegance

If you don’t know Ruby please take a few moments and look at code below. You may like it.

w = %w[a c d b e] # same as w = ["a", "c", "d", "b", "e"]
w.sort #=> ["a", "b", "c", "d", "e"]
w.sort.reverse #=> ["e", "d", "c", "b", "a"]
w.sort { |a,b| b<=>a } #=> ["e", "d", "c", "b", "a"]

w.reduce(:+) #=> "acdbe"
w.map(&:upcase) #=> ["A", "C", "D", "B", "E"]

w.include? "a" #=> true

(1..8).select(&:even?) #=> [2, 4, 6, 8]
(1..8).reject(&:even?) #=> [1, 3, 5, 7]

langs = %w[ruby python perl] # same as langs = ["ruby", "python", "perl"]

langs.group_by(&:chr) #=> {"r"=>["ruby"], "p"=>["python", "perl"]}
langs.map(&:capitalize) #=> ["Ruby", "Python", "Perl"]

As they say:

The beauty of Ruby is found in its balance between simplicity and power.

If after this your mouth is watering, you can try Ruby online.

« Quality Is Overrated Breaking The Rules »

Comments

Copyright © 2019 - Kresimir Bojcic (LinkedIn Profile)