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(&:to_i) rescue nil
end
p extract('123456789')
#=> [1234, 56, 789]
p extract('123456789012')
#=> nil