Pritesh Jain
Pritesh Jain

Reputation: 9146

Splitting strings in Ruby

I want to split a string:

"00 85 00 04 79 E5 0B B5 82 AE C7 C9 96 37 93 AE"

into two small strings like:

string1 => "00 85 00 04"
string2 => "79 E5 0B B5 82 AE C7 C9 96 37 93 AE"

I tried using arrays but would like to try something new.

Upvotes: 0

Views: 445

Answers (4)

DigitalRoss
DigitalRoss

Reputation: 146073

Apparently your split will be based on the interpreted contents of the string, and since that seems to be numeric, I would suggest first converting it to an array and operating directly on the real data, not on the string representation of it.

However, there is a way to split at a word boundary based on the content, but without eating any of the content, by using the zero-width lookahead pattern. You can thrown in some word boundary and space-eating patterns too:

s.split(/\b *(?=79)\b/)

Upvotes: 0

user483040
user483040

Reputation:

The answer to this depends upon other information you might provide: is the first string of a known length? What conceptually defines where you want the split to occur.

In your example you might do:

s = "00 85 00 04 79 E5 0B B5 82 AE C7 C9 96 37 93 AE"

l = s.split("04")

str0 = l[0] + "04"
str1 = l[1]

Or you could slice just like you might an array/list

Upvotes: 0

Fredrik Pihl
Fredrik Pihl

Reputation: 45662

Great place with a lot of examples in all sorts of languages like, python, perl, ruby and others pleac ruby string section.

The "great" thing is that all the different languages solve the same problems, making it easy to compare solutions between languages.

Upvotes: 1

fl00r
fl00r

Reputation: 83680

You don't need split here.

sample_string = "00 85 00 04 79 E5 0B B5 82 AE C7 C9 96 37 93 AE"
string1, string2 = sample_string[0, 11], sample_string[12..-1]
string1
#=> "00 85 00 04"
string2
#=> "79 E5 0B B5 82 AE C7 C9 96 37 93 AE"

But it is not clear what "pattern" do you want to use to cut original string.

Upvotes: 4

Related Questions