Ruby设计问题

Hun*_*len 1 ruby initialization

概观

我正在编写一个Ruby程序,它使用来自mysql查询的数据来创建图表URL.最近出现了一项新要求,我们可能需要在未来创建带有分组条形图的图形.因此,我可以拥有任意数量的数据,而不是拥有一组数据.现在我的BarChart对象的构造函数只接受一个数据数组,我正在寻找类似于Ruby的方法来允许多个数据数组.

当前构造函数

    #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
Run Code Online (Sandbox Code Playgroud)

我的尝试

我最初的想法是使用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
Run Code Online (Sandbox Code Playgroud)

这是一个不错的主意吗?或者有更好的方法去做吗?

谢谢

Jer*_*man 7

就个人而言,当你有这么多参数时,我会使用一个选项哈希.

def initialize(options = {})
  options = { default options here, if applicable }.merge(options)
  ...
end
Run Code Online (Sandbox Code Playgroud)

这样你就可以像这样构建你的类:

MyClass.new(:title => "Awesome Graph", :data => [[1,2,3], [4,5,6]], ...)
Run Code Online (Sandbox Code Playgroud)

我发现这种方法使你的方法调用更具可读性,因此你没有一个构造函数调用,它具有很长的数字和字符串参数序列,其含义可能很难确定.这也为您提供了一种使用默认值添加任意数量的可选参数的自然方法.