Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string in half, into two variables, in one statement?

Tags:

string

ruby

I want to split str in half and assign each half to first and second

Like this pseudo code example:

first,second = str.split( middle )
like image 426
localplutonium Avatar asked Feb 28 '26 01:02

localplutonium


2 Answers

class String
  def halves
    chars.each_slice(size / 2).map(&:join)
  end
end

Will work, but you will need to adjust to how you want to handle odd-sized strings.

Or in-line: first, second = str.chars.each_slice(str.length / 2).map(&:join)

like image 71
ForeverZer0 Avatar answered Mar 02 '26 15:03

ForeverZer0


first,second = str.partition(/.{#{str.size/2}}/)[1,2]

Explanation

You can use partition. Using a regex pattern to look for X amount of characters (in this case str.size / 2).

Partition returns three elements; head, match, and tail. Because we are matching on any character, the head will always be a blank string. So we only care about the match and tail hence [1,2]

like image 26
vol7ron Avatar answered Mar 02 '26 14:03

vol7ron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!