Small Sample of Ruby Elegance

1 min read Original article ↗
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"]