Ruby - How to keep white spaces when returning all even values in a string?

Question

I'm trying to make a code that returns all the even values in a string. The code I created seems to do that, but it won't return the white spaces and so the final test fails. Can someone help me to understand why it returns all the letters, but none of the whitespaces?

# Every Other Letter Define a method, #every_other_letter(string), 
# that accepts a string as an argument. This method should return a 
# new string that contains every other letter of the original string, 
# starting with the first character. Treat white-space and punctuation 
# the same as letters.

def every_other_letter(string)
  idx = 0
  final = []

  while idx < string.length 
    letters = string[idx].split
    final = final + letters
    idx = idx + 2
  end

  p final = final.join
end

puts "------Every Other Letter------"
puts every_other_letter("abcde") == "ace"
puts every_other_letter("i heart ruby") == "ihatrb"
puts every_other_letter("an apple a day...") == "a pl  a.."

and this returns:

------Every Other Letter------
"ace"
true
"ihatrb"
true
"apla.."
false
=> nil

Show source
| ruby   | while-loop   | whitespace   2017-11-29 21:11 2 Answers

Answers to Ruby - How to keep white spaces when returning all even values in a string? ( 2 )

  1. 2017-11-29 21:11

    The problem is, as pointed @Sergio, that you're using split over a single char, so, you're "converting" that letter in an array. What you can do is just to push the string[idx] to final and it works for you that way.

    In other way you could split the string, using select get the chars where the index is even, and then join them:

    p "an apple a day...".chars.select.with_index { |_, i| i.even?  }.join == "a pl  a.." # true
    
  2. 2017-11-29 23:11

    Just another way to get all even-index characters, using a regular expression to grab pairs and replacing each pair by just its first character:

    "abcd fghi".gsub(/(.)./, '\1')
    => "ac gi"
    

    Or find them and join them:

    "abcd fghi".scan(/(.).?/).join
    => "ac gi"
    

Leave a reply to - Ruby - How to keep white spaces when returning all even values in a string?

◀ Go back