Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何从命名顺序中获取整数索引_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 如何从命名顺序中获取整数索引

Ruby on rails 如何从命名顺序中获取整数索引,ruby-on-rails,ruby,Ruby On Rails,Ruby,这可能很明显,但我找不到答案 如何从命名顺序获取整数索引,如: { :first => 0, :second => 1, :third => 2, :fourth => 3 } Ruby或Rails中是否内置了这样的功能 谢谢 更新 谢谢你的回复。以下是我采用的解决方案: def index_for(position) (0..4).to_a.send(position) end 但是数组最多只支持第五个,所以只能支持第五个。我通常保留一个哈希键数组来维持顺序。

这可能很明显,但我找不到答案

如何从命名顺序获取整数索引,如:

{ :first => 0, :second => 1, :third => 2, :fourth => 3 }
Ruby或Rails中是否内置了这样的功能

谢谢

更新

谢谢你的回复。以下是我采用的解决方案:

def index_for(position) 
  (0..4).to_a.send(position)
end

但是数组最多只支持第五个,所以只能支持第五个。

我通常保留一个哈希键数组来维持顺序。

您使用的是什么版本的Ruby?对于Ruby1.8,您不能这样做,因为在这个版本中,哈希是一个无序的集合。这意味着在插入键时,不会保留顺序。当您迭代散列时,键的返回顺序可能与插入键的顺序不同

但在Ruby 1.9中,它已经发生了变化。

查看其中的混合。
我认为每个带有索引的_都是您要搜索的:

# Calls block with two arguments, the item and its index, for each item in enum. 

hash = Hash.new
%w(cat dog wombat).each_with_index {|item, index|
  hash[item] = index
}
hash   #=> {"cat"=>0, "wombat"=>2, "dog"=>1}

如果需要排序索引,则可能需要将数组和

keys = [ :first, :second, :third, :fourth ]
hash = { :first => 0, :second => 1, :third => 2, :fourth => 3 }
hash.each_key { |x| puts "#{keys.index(x)}" }

上述方法只适用于1.9版本。

对于追随者来说,语言学宝石显然也可以做类似的事情

虽然这对Ruby 1.8是正确的,但在Ruby 1.9版本中有所改变。哈希保留Ruby 1.9中的插入顺序。抱歉挑剔:)不,谢谢你提供有用的信息!我将更新帖子以使其正确。