Reputation: 2562
I am trying to get the first half of a string. If the string length is an odd number, then round up. I am bit stuck on getting a half of a string.
def get_first_half_of_string(string)
if string.size % 2 == 0
string[1,4]
else
string[1,5]
end
end
puts get_first_half_of_string("brilliant")
This returns rilli
Upvotes: 1
Views: 1750
Reputation: 3298
When calling str[start, length]
you need to use 0
, not 1
, as the start point. For the length you should just be able to divide the length by 2, so your method body only needs string[0, (string.length.to_f / 2).ceil]
https://ruby-doc.org/core-2.2.0/String.html#method-i-5B-5D
Upvotes: 2
Reputation: 11
Maybe you could divide the string size in half and round up if it is odd:
half = (string.size/2.to_f).ceil
string[0,half]
Upvotes: 1
Reputation: 131
Following previous answers, you could open String
class:
class String
def first_half
self[0,(self.size/2.to_f).ceil]
end
end
So you can do:
"ruby".first_half
=> "ru"
"hello".first_half
=> "hel"
Upvotes: 0
Reputation: 106812
I would do something like this:
def first_half_of_string(string)
index = (string.size.to_f / 2).ceil
string[0, index]
end
first_half_of_string("brilliant")
#=> "brill"
Upvotes: 1