Reputation: 178
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??
Upvotes: 0
Views: 440
Reputation: 5205
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).
Upvotes: 0
Reputation: 50948
i = gets
returns the string with the newline character at the end, i.e. your string is "102\n"
, thus has length 4.
Upvotes: 2