Overview
I am writing a Ruby program that uses data from mysql queries to create chart URLs. A new requirement has recently surfaced where we could need to created graphs with grouped bars in the future. So instead of having one set of data, I could have any number of sets. Right now the constructor for my BarChart object only takes a single array of data, and I am looking Ruby-like ways of allowing more than one array of data.
Current Constructor
#constructor
#title The title of the graph
#data The data that will go in the bar chart
#labels The labels that match the data
#x_axis_label The label for the x axis
#y_axis_label The label for the y axis
def initialize(title, data, labels, x_axis_label, y_axis_label)
@title, @data1, @labels, @x_axis_label, @y_axis_label =
title, data, labels, x_axis_label, y_axis_label
super(@title, @@type, @@size)
@url = to_url()
end
My attempt
My initial thought was to use var args.
#constructor
#title The title of the graph
#data The data that will go in the bar chart
#labels The labels that match the data
#x_axis_label The label for the x axis
#y_axis_label The label for the y axis
def initialize(title, *data, labels, x_axis_label, y_axis_label)
.....
end
Is this a decent idea? or is there a better way to go about it?
Thanks
Personally, when you have this many arguments, I would use an options hash.
So that you can construct your class like this:
I find this approach makes your method calls much more readable, so you don’t have a constructor call which has a long sequence of number and string arguments for which the meaning may be difficult to determine. This also gives you a natural way to add an arbitrary amount of optional parameters with default values.