Some suggestions:
- You should better use
swells
in plural thanswell
for a set of things. - For things of varying length, Array is the best fit. When referring to a particular element of an Array, you should use the
[]
method instead of methods like1
,2
, etc. (Probably that is not possible in the first place). In that case, note that you should start from0
, not1
. - You can easily get the number of swells by applying the
length
method on the swells. You should not have a specific methodnumswells
for that unless it will be used particularly frequently.
I would do something like this:
data =
"| 15 11 | 0.65 3 | 0.47 3.7 73 | 0.38 10.7 186 | 0.23 4.1 352 |"
class Forecast
attr_reader :date, :swells
def initialize string
_, date, _, swells = string.split("|", 4)
@date = date.scan(/\d+/).join(":")
@swells = swells.scan(/[^\|]+/).select{|s| s =~ /\S/}.map{|s| Swell.new(s)}
end
end
class Swell
attr_reader :height, :tp, :direction
def initialize string
@height, @tp, @direction = string.split(/\s+/).drop(1).map(&:to_f)
end
end
@forecast = Forecast.new(data)
p @forecast.date
p @forecast.swells.length
p @forecast.swells[0].height
p @forecast.swells[0].direction
p @forecast.swells[2]
#=> "15:11"
#=> 3
#=> 0.47
#=> 73.0
#=> #<Swell:0x000000016401d0 @height=0.23, @tp=4.1, @direction=352.0>