获取组合数组和常量的哈希

时间:2013-12-28 16:53:38

标签: ruby-on-rails ruby arrays hash

我有这个数组

Animals = ['sad cat','happy dog','vegetarian fish','hungry shark']

和这些常量

SAD_CATS = {somekey : somevalue, otherkey : othervalue}
HAPPY_DOGS = {somekey : somevalue, otherkey : othervalue}
VEGETARIAN_FISH = {somekey : somevalue, otherkey : othervalue}
HUNGRY_SHARKS = {somekey : somevalue, otherkey : othervalue}

哪种方法最好?

RESULT = {'sad-cat' => SAD_CATS ,'happy-dog' => HAPPY_DOGS ,'vegetarian-fish' => VEGETARIAN_FISHES ,'hungry-shark' => HUNGRY_SHARKES }

请注意,constas是数组的复数和上位值。

我试过

RESULT = Animals.map(:&parameterize).map(:&upcase) 

但它没有像我期望的那样起作用

EDITED

因为 FISHES 不是英文

4 个答案:

答案 0 :(得分:0)

如果您对基于Rails的解决方案感到满意,并且愿意更改“fish”和“shark”复数以匹配Rails默认值,则可以使用以下内容。我修改了常量的值,使输出的验证更具可读性。

Animals = ['sad cat','happy dog','vegetarian fish','hungry shark']

SAD_CATS = :cat_constant
HAPPY_DOGS = :dog_constant
VEGETARIAN_FISH = :fish_constant
HUNGRY_SHARKS = :shark_constant

Hash[Animals.map do |a|
  [a.gsub(' ','-'), a.gsub(' ','_').pluralize.upcase.constantize]
  end]

 => {"sad-cat"=>:cat_constant, "happy-dog"=>:dog_constant, "vegetarian-fish"=>:fish_constant, "hungry-shark"=>:shark_constant}

如果您只想要一个Ruby解决方案,可以使用它。当然,如果您愿意,可以避免String的猴子修补。

Animals = ['sad cat','happy dog','vegetarian fish','hungry shark']

SAD_CATS = :cat_constant
HAPPY_DOGS = :dog_constant
VEGETARIAN_FISHES = :fish_constant
HUNGRY_SHARKES = :shark_constant

class String
  PLURALIZATION_EXCEPTIONS = {shark: 'es', fish: 'es'}
  def pluralize
    self+(PLURALIZATION_EXCEPTIONS[self.split(' ')[-1].to_sym] || 's')
  end
end

Hash[Animals.map do |a|
  [a.gsub(' ','-'), self.class.const_get(a.pluralize.gsub(' ','_').upcase)]
  end]

 => {"sad-cat"=>:cat_constant, "happy-dog"=>:dog_constant, "vegetarian-fish"=>:fish_constant, "hungry-shark"=>:shark_constant} 

答案 1 :(得分:-1)

我会选择:

animals.each_with_object({}) do |a, h| 
 h[a.parameterize] = a.pluralize.upcase.tr(' ', '_').constantize
end

注意:复数形式的“fish”是相同的

文档:

http://apidock.com/rails/String/parameterize

http://apidock.com/rails/String/pluralize

http://apidock.com/rails/String/constantize

答案 2 :(得分:-1)

数组中的元素表示单数实体,而您的常量(忽略大小写)表示多个实体('sad cat'与'SAD_CATS'或'素食鱼'与'VEGETARIAN_FISHES')。

我怀疑在Ruby或Rails中是否可以实现这种自动复数。

但是,如果你的常量是单数,如下:

SAD_CAT         = {somekey: somevalue, otherkey: othervalue}
HAPPY_DOG       = {somekey: somevalue, otherkey: othervalue}
VEGETARIAN_FISH = {somekey: somevalue, otherkey: othervalue}
HUNGRY_SHARK    = {somekey: somevalue, otherkey: othervalue}

然后,以下内容将为您提供所需的结果:

RESULT = Hash[Animals.collect { |x| [x, eval(x.gsub(' ', '_').upcase)] }]

希望这有帮助。

答案 3 :(得分:-1)

这是你的解决方案:

RESULT = Animals.inject({}) do |h, animal|
  h.merge animal.parameterize => animal.pluralize.underscore.gsub(' ', '_').upcase.constantize
end

请注意,鲨鱼的复数不是“鲨鱼”,而是“鲨鱼”,“鱼”的复数是“鱼”。