The easiest way to answer the first part is, as always, to compare it with your real data. For example:
require 'benchmark' Benchmark.bm do |x| x.report { 50000.times { a = ' a@b.c '.split('@')[0] } } x.report { 50000.times { a = ' a@b.c '[/[^@]+/] } } end
says (according to my setup):
user system total real 0.130000 0.010000 0.140000 ( 0.130946) 0.090000 0.000000 0.090000 ( 0.096260)
So, the regex solution looks a little faster, but the difference is barely noticeable even at 50,000 iterations. OTOH, the regular expression says exactly what you mean ("give me everything to the first @ "), while the split solution will get the desired result in a slightly circular way.
The split approach is probably slower because it needs to scan the entire string to break it into pieces, then build an array of parts and finally extract the first element of the array and discard the rest; I do not know if the virtual machine is enough to understand that it does not need to build an array in order to work a little fast.
Regarding your second question, tell me what you mean:
my_string[/[^.]+/]
If you want everything before the first period, then say "everything before the period", and not "the first fragment, which consists of these characters (which do not contain a period)".
mu is too short
source share