String reversal one-liner
Published on 05 Jul 2020
reverse = ->(str) {Array.new(str.length) {|i| str[(i + 1) * -1]}.join}
reverse["Hello World"]
=> "dlroW olleH"
Steps
Code | Explanation | Return Value |
---|---|---|
Array.new |
Create an empty Array | [] |
str.length |
The number of characters in a String, including whitespace | 11 |
Array.new(str.length) |
Create an Array with ‘n’ nil elements |
[nil, nil, nil... ] |
str[(i + 1) * -1] |
Replace nil with the ‘nth-from-the-end’ character of the String |
When i = 0 , str[-1] |
[...].join |
Convert elements to Strings and concatenate them without a delimiter | [d,l,r,o,W] => 'dlroW' |
all tags
activerecord android annoyances api apt arch array artix atom az3w backend bash blog browser bug callback career cli cloud code coding config configuration cp crud css database db design devops django email erp filter fugitive gif gist git gnome grep hebrew http ide isbn-fetcher iso javascript job search js kanban kanban\ kindle koans linux logger manjaro map markdown microservices mobi mtp neovim nodejs packages pastbin patch post python rails reduce refactoring rest routes rspec ruby scripting security sed shell sql string_replacement study tdd terminal testing version_control vim walkthrough workflow