Using Tuples in Ruby?

后端 未结 7 1030
醉话见心
醉话见心 2020-12-24 00:24

Does anyone use tuples in Ruby? If so, how may one implement a tuple? Ruby hashes are nice and work almost as well, but I\'d really like to see something like the Tuple clas

7条回答
  •  萌比男神i
    2020-12-24 01:03

    Arrays are cool to use as tuples because of destructuring

    a = [[1,2], [2,3], [3,4]]
    a.map {|a,b| a+b }
    

    Struct give you convenient . accessors

    Person = Struct.new(:first_name, :last_name)
    ppl = Person.new('John', 'Connor')
    ppl.first_name 
    ppl.last_name
    

    You can get the convenience of both worlds with to_ary

    Person = Struct.new(:first_name, :last_name) do
      def to_ary
        [first_name, last_name]
      end
    end
    # =>
    [
      Person.new('John', 'Connor'), 
      Person.new('John', 'Conway')
    ].map { |a, b| a + ' ' + b  }
    # => ["John Connor", "John Conway"]
    

提交回复
热议问题