views:

207

answers:

3

I'm trying to find the first and second half of a string of numbers with ruby ignoring the central digit if the length is odd i.e input = "102" first_half = "1" second_half = "2"

using this code

i = gets
first_half=i[0..(i.length / 2 - 1).floor]
second_half = i[i.length -first_half.length)..i.length - 1]
print "#{first_half}\n#{second_half}"

however for this input the output is 10 ("\n") 2

the code does however work correctly in irb. Can anyone see what the problem I have is??

+2  A: 
i = gets

returns the string with the newline character at the end, i.e. your string is "102\n", thus has length 4.

balpha
thanks so much new to ruby :S
dunkyp
+1  A: 

use i=gets.chomp

igor_b
A: 
i = gets.chomp
first_half=i[0..(i.length / 2 - 1).floor]
second_half = i[(i.length - first_half.length).. i.length - 1]
print "#{first_half}\n#{second_half}"

iano:Desktop ian$ ruby stack.rb 
102
1
2

Your problem (though there were some minor syntax errors) is that you have to chomp (removing the "\n" character at the end of the input string).

iano