在Ruby中使用元组?

3okqufwl  于 4个月前  发布在  Ruby
关注(0)|答案(7)|浏览(56)

有人在Ruby中使用元组吗?如果有的话,如何实现元组?Ruby哈希很好,几乎可以工作,但我真的很想看到类似Python中的Tuple类,在那里你可以使用.符号来找到你正在寻找的值。我想要这个,这样我就可以创建D的实现,类似于Python的Dee

cig3rfwq

cig3rfwq1#

OpenStruct
简单的例子:

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

字符串

tez616oj

tez616oj2#

基于你谈论哈希和. notation的事实,我假设你指的是一种不同于(1. "a")排序的元组。你可能在寻找Struct类。例如:

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

字符串

rjjhvcjd

rjjhvcjd3#

虽然这不是严格意义上的元组(不能用点表示成员),但你可以从一个列表中分配一个变量列表,这通常会解决当你在一个返回值列表之后ruby是按值传递的问题。
例如

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

字符串

gdx19jrr

gdx19jrr4#

数组作为元组使用很酷,因为它可以解构

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

字符串
结构给予方便的.访问器

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


您可以通过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"]

2w2cym1i

2w2cym1i5#

我是Gem for Ruby tuples的作者。
你有两个类:

  • Tuple一般
  • Pair特别是

你可以用不同的方式初始化它们:

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

字符串
这两个类都有一些辅助方法:

  • length/arity-返回元组中的值的数量
  • first/last/second(仅对)-返回相应的元素
  • [],用于访问特定元素
u3r8eeie

u3r8eeie6#

你可以用这个技巧来模拟Scala元组:

Tuple = Struct.new(:_1, :_2)

2.2.5 :003 > t = Tuple.new("a", "b")
 => #<struct Tuple _1="a", _2="b">
2.2.5 :004 > t._1
 => "a"
2.2.5 :005 > t._2
 => "b"

字符串
但这里你不能有解构

2.2.5 :012 > a, b = t
 => {:_1=>"a", :_2=>"b"}
2.2.5 :013 > a
 => {:_1=>"a", :_2=>"b"}
2.2.5 :014 > b
 => nil


但多亏了这个技巧:https://gist.github.com/stevecj/9ace6a70370f6d1a1511解构将工作:

2.2.5 :001 > Tuple = Struct.new(:_1, :_2)
 => Tuple
2.2.5 :002 > t = Tuple.new("a", "b")
 => #<struct Tuple _1="a", _2="b">
2.2.5 :003 > t._1
 => "a"
2.2.5 :004 > class Tuple ; def to_ary ; to_a ; end ; end
 => :to_ary
2.2.5 :005 > a, b = t
 => #<struct Tuple _1="a", _2="b">
2.2.5 :006 > a
 => "a"
2.2.5 :007 > b
 => "b"

bf1o4zei

bf1o4zei7#

你可以做一些类似于解构的事情:

def something((a, b))
  a + b
end

p something([1, 2])

字符串
这将按预期打印出3

相关问题