I'm looking for a more elegant solutions of this task.

Task: Given a string, print its even-indexed and odd-indexed characters as space-separated strings on a single line.

Input Format: The first line contains an integer (the number of test cases). Each line of the subsequent lines contain a string.

puts "Input a number of test cases"
t = gets.to_i
t.times do
  puts "Input a string please"  
  s = gets.strip
  z = s.split(//)
  b = z.each_with_index.sort_by { |i, x| [x.even? ? 0 : 1, x] }
  b.map { |i, x| print i if x.even? }
  print " "
  b.map { |i, x| print i if x.odd? }

1 Answer 1


It's a good idea to become familiar with all the methods on Array and Enumerable. It just so happens that Enumerable has a method called partition that has a purpose of dividing an array into .two parts (e.g. even and odd). It'll help tidy up your code.

So let's use partition on the array of chars and partition based on index.

parts = s.chars.partition.with_index{|_,i| i.even?}

Note since we are only using the index, the actual character is unimportant so I used _ instead of a variable name in the partition block. Now you have two arrays of characters--let's join each array so that you have a single array with two strings:

strings = parts.map(&:join)

If you don't know about &:join it is a shortcut for {|a| a.join} (using Symbol#to_proc if you want to read up on it).

Then, finally print it. Note that in your code, you intermingle printing with manipulation. This is best avoided if you can; print only once you have things in final form.

print strings.join(' ')

The above could all be put together in one line if you'd rather:

print s.chars.partition.with_index{|_,i| i.even?}.map(&:join).join(' ')
  • 1
    \$\begingroup\$ thanks for the answer, I was sure there is a magiс one-liner for this thing :). \$\endgroup\$ May 29, 2017 at 13:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.