标题大写 [英] Capitalizing titles

查看:39
本文介绍了标题大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一种将标题大写的方法.它应该不是每个单词都大写,如果你愿意的话,只应该大写.有时,它必须大写每个单词.也许我需要为小词添加一个例外.它是 Ruby 教程的一部分,我不能使用 Rails titleize 方法.这是我到目前为止所拥有的.如果你能帮忙,请告诉我.

I'm trying to write a method that will capitalize titles. It should capitalize not every word, but only the big words if you will. Sometimes, it has to capitalize every word. Maybe I need to add an exception for the little words. It's part of a Ruby tutorial, and I can't use the Rails titleize method. Here is what I have so far. Please let me know if you can help.

def titleize(name)
  name.split(" ").each {|word| word.capitalize!}.join (" ")
end

推荐答案

基于 Josh Voigts 评论:

Building off of Josh Voigts comment:

def titleize(name)
  lowercase_words = %w{a an the and but or for nor of}
  name.split.each_with_index.map{|x, index| lowercase_words.include?(x) && index > 0 ? x : x.capitalize }.join(" ")
end

您可能希望将 lowercase_words 设为常量并将其移出函数,因为它们永远不会改变.

You might want make lowercase_words a constant and move it out of the function since they won't ever change.

这篇关于标题大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆