好的,所以我试图删除下划线,如某些假期中所见(例如,fourth_of_july)。然后我想把每个词都大写。
预期结果:fourth_of_july>七月四日
所以这是我的代码:
holiday_dec = {
:winter => {
:christmas => ["Lights", "Wreath"],
:new_years => ["Party Hats"]
},
:summer => {
:fourth_of_july => ["Fireworks", "BBQ"]
},
:fall => {
:thanksgiving => ["Turkey"]
},
:spring => {
:memorial_day => ["BBQ"]
}
}
def all_supplies_in_holidays(holiday_hash)
holiday_hash.each do |seasons, holidays|
holidays.each do |holidays, supplies|
puts "#{seasons.to_s.capitalize}:"
puts " #{holidays.to_s.tr("_"," ").capitalize}: #{supplies.join(", ")}"
end
end
end
all_supplies_in_holidays(holiday_dec)
答案 0 :(得分:14)
在Rails中,您可以使用titleize
'fourth_of_july'.titleize => "Fourth Of July"
答案 1 :(得分:6)
你可以使用这个衬垫
str.split('_').map(&:capitalize).join(' ')
这需要一个字符串str
并将其拆分为下划线所在的位置,然后将每个单词大写,然后将这些单词与空格连接在一起。实施例
"fourth_of_july".split('_') -> ["fourth", "of", "july"]
["fourth", "of", "july"].map(&:capitalize) -> ["Fourth", "Of", "July"]
["Fourth", "Of", "July"].join(' ') -> "Fourth Of July"
答案 2 :(得分:1)
使用递归我们可以浏览您的嵌套哈希,找到所有密钥并应用更改:
def key_changer hash
hash.map do |k,v|
[ k.to_s.scan(/[a-zA-Z]+/).map(&:capitalize).join(' '),
v.class == Hash ? key_changer(v) : v ]
end.to_h
end
key_changer holiday_dec #=>
#{ "Winter" => { "Christmas" => ["Lights", "Wreath"],
# "New Years" => ["Party Hats"] },
# "Summer" => { "Fourth Of July" => ["Fireworks", "BBQ"] },
# "Fall" => { "Thanksgiving" => ["Turkey"] },
# "Spring" => { "Memorial Day" => ["BBQ"]}
#}
这不完全是你所要求的(只有在回答后才能实现),但我会留下这个答案,因为你可能认为它有用。
答案 3 :(得分:0)
holiday_dec.each_with_object({}) { |(k,v),h|
h[k] = v.each_with_object({}) { |(kk,vv),g|
g[kk.to_s.split('_').map { |s| s[0]=s[0].upcase; s }.join(' ')] = vv } }
#=> {:winter=>{"Christmas"=>["Lights", "Wreath"], "New Years"=>["Party Hats"]},
# :summer=>{"Fourth Of July"=>["Fireworks", "BBQ"]},
# :fall=>{"Thanksgiving"=>["Turkey"]},
# :spring=>{"Memorial Day"=>["BBQ"]}}
我使用的是s[0]=s[0].upcase; s
而不是s.capitalize
,因为后者会在第一个小写字母后转换所有字符(以及将第一个字母大写),但提问者并未说明需要或如果在每个单词的第一个字符后面可能有大写字母。
答案 4 :(得分:0)
我来到这里寻找一种方法来修改带下划线的字符串,使其更像类名。 Rails有String#classify
。
irb> 'some_class_string'.classify
=> "SomeClassString"