Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Tuples in Ruby?

People also ask

How do you use tuples in Ruby?

A tuple can be made using #new or #[] just as one builds an array, or using the #to_t method on a string or array. With a string tuple remembers the first non-alphanumeric character as the tuple divider.

Does Ruby support tuples?

In Python a Tuple is used with parenthesis (1,2,3). In Ruby things aren't as fixed so you don't have Tuples as a common things to access.

How do you add to an array in Ruby?

push() is a Ruby array method that is used to add elements at the end of an array. This method returns the array itself.


OpenStruct?

Brief example:

require 'ostruct'

person = OpenStruct.new
person.name    = "John Smith"
person.age     = 70
person.pension = 300

puts person.name     # -> "John Smith"
puts person.age      # -> 70
puts person.address  # -> nil

Based on the fact that you talk about hashes and . notation I'm going to assume you mean a different kind of tuple than the (1. "a") sort. You're probably looking for the Struct class. eg:

Person = Struct.new(:name, :age)
me = Person.new
me.name = "Guy"
me.age =  30

While this isn't strictly a tuple (can't do dot notation of members), you can assign a list of variables from a list, which often will solve issues with ruby being pass-by-value when you are after a list of return values.

E.g.

:linenum > (a,b,c) = [1,2,3]
:linenum > a
  => 1
:linenum > b
  => 2
:linenum > c
  => 3

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"]

I'm the author of Gem for Ruby tuples.

You are provided with two classes:

  • Tuple in general
  • Pair in particular

You can initialize them in different ways:

Tuple.new(1, 2)
Tuple.new([1, 2])
Tuple(1, 2)
Tuple([1, 2])
Tuple[1, 2]

Both of the classes have some auxiliary methods:

  • length / arity - which returns number of values inside tuple
  • first / last / second (only pair) - which returns a corresponding elements
  • [] that gives you an access to a particular elements