Extracting data from a string I created a method that takes a string value with a fixed length of 9 characters and extracts three values, house (4 characters), level (2), door (3). If the input value has another length than 9 then the method should return nil.

I found several ways to implement the method, but which implementation should I prefer and why?

def extract(value)
  return nil unless value.length == 9
  [value[0..3].to_i, value[4..5].to_i, value[6..8].to_i]
end

require 'scanf'

def extract(value)
  return nil unless value.length == 9
  value.scanf('%4d%2d%3d')
end

def extract(value)
  value.match(/^(\d{4})(\d{2})(\d{3})$/).captures.map(&amp;:to_i) rescue nil
end

p extract('123456789')
#=&gt; [1234, 56, 789]
p extract('123456789012')
#=&gt; nil
My Thoughts

I haven't profiled any of these, but I'm going to assume speed is not a priority.

I like #2 the best.  It is clean and simple, and easy to understand what the code is doing at a glance.

I think #1 is ugly, and the sequential array slicing makes me nervous and seems easy to break.  If your number sizes change at some point in the future, this one would be the hardest to modify.

I think #3 is better, but not as clear or concise as #2.