Hackerrank Ruby - Enumerable - collect Solution

Hackerrank Ruby - Enumerable - collect Solution

.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue}

Beside simple methods to iterate over objects, Ruby Enumerable provides a number of important higher order constructs that we shall explore in further challenges. One of such important methods is collect method, also known as map.

map as the name may suggest, takes a function and maps (applies) it to a collection of values one by one and returns the collection of result.

That is,

This single powerful method helps us to operate on a large number of values at once.

For example,>>> [1,2,3].map { |x| 2*x }=> [2, 4, 6]>>> {:a=>1, :b=>2, :c=>3}.collect { |key, value| 2*value }=> [2, 4, 6]

Note that these methods are different from each in the respect that these methods return a new collection while former returns the original collection, irrespective of whatever happens inside the block.

In this challenge, your task is to write a method which takes an array of strings (containing secret enemy message bits!) and decodes its elements using ROT13 cipher system; returning an array containing the final messages.

For example, this is how ROT13 algorithm works,

Original text:Why did the chicken cross the road?Gb trg gb gur bgure fvqr!

On application of ROT13,Jul qvq gur puvpxra pebff gur ebnq?To get to the other side!

Solution in ruby

Approach 1.


def rot13(secret_messages)
    secret_messages.map{|c| c.tr('a-z', 'n-za-m')}
end


Approach 2.


def rot13(secret_messages)
    secret_messages.map { |message| message.tr("a-z", "n-za-m") }
end


Approach 3.


def rot13(secret_messages)
  # your code here
    secret_messages.map {|c| c.tr("a-z", "n-za-m") }
end


Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe