Ruby: collect, chr, join, sort
Define a function named sort_transform
which receives an array of ASCII codes, e.g. [111, 112, 113, 114, 115, 113, 114, 110]
.
def sort_transform a
Assign given array a
to new variable a1
:
let a1 = a
Define a nested function named c
which receives array a1
, and returns a map. c()
will be called four times in the return statement.
def c(a1)
return [0,1,-2,-1].collect{ |x| a1[x].chr }.join('')
end
The array [0,1,-2,-1]
passed to collect
contains index values to map the first two and last two characters. The chr
method converts each ASCII code to a character string.
The function sort_transform
returns various strings of characters joined with hyphens, e.g. oprn-nors-sron-nors
.
return [c(a1), c(a1.sort), c(a1.sort { |x,y| y <=> x }), c(a1.sort)].join('-')
In the return statement above, the array sort instruction c(a1.sort { |x,y| y <=> x })
uses the spaceship operator <=>
to invert the sorting method from default ascending mode to descending mode, e.g. y <=> x
.
Run the script
p(sort_transform([111, 112, 113, 114, 115, 113, 114, 110]), "oprn-nors-sron-nors")
The string returned should match.