0

I am currently looking for the fastest way to parse a string in Ruby. The string has the format:

"#{String1}>#{String2}(#{Integer})", for example "Hello>World(25)"

and I am looking to retrieve the values of String1, String2, and Integer out of it. My current way of doing it is just

s1 = "Hello"
s2 = "World"
i = 25
str = "#{s1}>#{s2}(#{i})"
str = str.split('>')
newStr = str[1].split('(')
str[1] = newStr[0]
str[2] = newStr[1].chomp(')').to_i
print(str)   # => ["Hello", "World", 25]`

I am looking for any way faster than this to speed up my program. Thanks.

4 Answers 4

2

String partition method is even faster than split method.

str = "Hello>World(25)"

a, _, b = str.partition('>')
b, _, c = b.partition('(')
c = c.to_i

puts a, b, c
Sign up to request clarification or add additional context in comments.

1 Comment

This is indeed the fastest way
1

If you want speed over readability, you're probably really close to the fastest you're going to get. I was able to shave a little bit of time off of your implementation by passing the optional limit parameter to split and omitting the chomp(')') which isn't needed:

  # Way #1
  str = str.split('>', 2)
  newStr = str[1].split('(', 2)
  str[1] = newStr[0]
  str[2] = newStr[1].to_i

or, at right about the same speed (it's faster in some runs, slower in others):

  # Way #2
  str = str.split(/[>(]/, 3)
  str[2] = str[2].to_i

1 Comment

Way #1 worked perfectly, chopped off ~5ms off of my average runtime. Way #2 added ~15ms to it however. Either way, way #1 answered my question perfectly. Thanks.
1

You could use regex capture groups to obtain these values:

str = "Hello>World(25)"
s1, s2, i = str.match(/(\w+)>(\w+)\((\d+)\)/i).captures

1 Comment

I just tested this method, and while it is much easier to read, it slows down the execution of my program by ~12%
0

You can use regex inside your #split method to achieve the same result:

string = "Hello>World(25)"
result = string.split(/[>,()]/)
result[-1] = result[-1].to_i

result
# => ["Hello", "World", 25]

Hope this helps!

1 Comment

I just tested this method, and while it is much easier to read, it slows down the execution of my program by ~9%

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.