I'm trying to get Rails to capitalize the first character of a string, and leave all the others the way they are. I'm running into a problem where "i'm from New York" gets turned into "I'm from new york."
我试图让Rails大写字符串的第一个字符,并让其他字符保持原样。我遇到了一个问题,“我来自纽约”变成了“我来自纽约”。
What method would I use to select the first character?
我用什么方法来选择第一个字符?
Thanks
谢谢
EDIT: I tried to implement what macek suggested, but I'm getting a "undefined method `capitalize'" error. The code works fine without the capitalize line. Thanks for the help!
编辑:我试图实现macek的建议,但是我得到了一个“未定义的方法”大写的“错误”。代码在没有大写行的情况下运行良好。谢谢你的帮助!
def fixlistname!
self.title = self.title.lstrip + (title.ends_with?("...") ? "" : "...")
self.title[0] = self.title[0].capitalize
errors.add_to_base("Title must start with \"You know you...\"") unless self.title.starts_with? 'You know you'
end
EDIT 2: Got it working. Thanks for the help!
编辑2:让它工作。谢谢你的帮助!
EDIT 3: Wait, no I didn't... Here's what I have in my list model.
编辑3:等等,不,我没有……这是我的列表模型。
def fixlistname!
self.title = self.title.lstrip + (title.ends_with?("...") ? "" : "...")
self.title.slice(0,1).capitalize + self.title.slice(1..-1)
errors.add_to_base("Title must start with \"You know you...\"") unless self.title.starts_with? 'You know you'
end
EDIT 4: Tried macek's edit, and still getting an undefined method `capitalize'" error. What could I be doing wrong?
编辑4:尝试macek的编辑,仍然得到一个未定义的方法“大写”错误。我做错了什么?
def fixlistname!
self.title = title.lstrip
self.title += '...' unless title.ends_with?('...')
self.title[0] = title[0].capitalize
errors.add_to_base('Title must start with "You know you..."') unless title.starts_with?("You know you")
end
EDIT 5: This is weird. I'm able to get rid of the undefined method error by using the line below. The problem is that it seems to replace the first letter with a number. For example, instead of capitalizing the y in You, it turns the y into a 121
编辑5:这很奇怪。我可以使用下面的行来消除未定义的方法错误。问题是它似乎用一个数字代替了第一个字母。例如,它不是把y大写,而是把y变成121
self.title[0] = title[0].to_s.capitalize
17 个解决方案
#1
84
Titleize will capitalise every word. This line feels hefty, but will guarantee that the only letter changed is the first one.
标题化将把每个字都大写。这句话让人感觉很沉重,但可以保证,唯一改变的是第一封信。
new_string = string.slice(0,1).capitalize + string.slice(1..-1)
Update:
更新:
irb(main):001:0> string = "i'm from New York..."
=> "i'm from New York..."
irb(main):002:0> new_string = string.slice(0,1).capitalize + string.slice(1..-1)
=> "I'm from New York..."
#2
111
This should do it:
这应该这样做:
title = "test test"
title[0] = title[0].capitalize
puts title # "Test test"
#3
48
You can use humanize. If you don't need underscores or other capitals in your text lines.
您可以使用人性化。如果你不需要下划线或其他大写字母在你的文本行。
Input:
输入:
"i'm from New_York...".humanize
Output:
输出:
"I'm from new york..."
#4
35
str = "this is a Test"
str.sub(/^./, &:upcase)
# => "This is a Test"
#5
20
As of Rails 5.0.0.beta4 you can use the new String#upcase_first
method or ActiveSupport::Inflector#upcase_first
to do it. Check this blog post for more info.
在Rails 5.0.0。您可以使用新的字符串#upcase_firstmethod或ActiveSupport::Inflector#upcase_first来完成它。查看这篇博文获得更多信息。
#6
14
An object oriented solution:
面向对象的解决方案:
class String
def capitalize_first_char
self.sub(/^(.)/) { $1.capitalize }
end
end
Then you can just do this:
然后你可以这样做:
"i'm from New York".capitalize_first_char
#7
6
Edit 2
I can't seem to replicate your trouble. Go ahead and run this native Ruby script. It generates the exact output your looking for, and Rails supports all of these methods. What sort of inputs are you having trouble with?
我似乎无法再现你的烦恼。继续运行这个原生Ruby脚本。它生成您需要的确切输出,Rails支持所有这些方法。你有什么问题吗?
#!/usr/bin/ruby
def fixlistname(title)
title = title.lstrip
title += '...' unless title =~ /\.{3}$/
title[0] = title[0].capitalize
raise 'Title must start with "You know you..."' unless title =~ /^You know you/
title
end
DATA.each do |title|
puts fixlistname(title)
end
__END__
you know you something WITH dots ...
you know you something WITHOUT the dots
you know you something with LEADING whitespace...
you know you something with whitespace BUT NO DOTS
this generates error because it doesn't start with you know you
output
You know you something WITH dots ...
You know you something WITHOUT the dots...
You know you something with LEADING whitespace...
You know you something with whitespace BUT NO DOTS...
RuntimeError: Title must start with "You know you..."
Edit
Based on your edit, you can try something like this.
根据您的编辑,您可以尝试如下内容。
def fixlistname!
self.title = title.lstrip
self.title += '...' unless title.ends_with?('...')
self.title[0] = title[0].capitalize
errors.add_to_base('Title must start with "You know you..."') unless title.starts_with?("You know you")
end
Original
This will do the trick
这样就可以了
s = "i'm from New York"
s[0] = s[0].capitalize
#=> I'm from New York
When trying to use String#capitalize
on the whole string, you were seeing I'm from new york
because the method:
当你试图用字符串#大写的时候,你会看到我来自纽约,因为这个方法:
Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.
返回第一个字符转换为大写,其余为小写的str副本。
"hello".capitalize #=> "Hello"
"HELLO".capitalize #=> "Hello"
"123ABC".capitalize #=> "123abc"
#8
6
my_string = "hello, World"
my_string.sub(/\S/, &:upcase) # => "Hello, World"
#9
6
str.sub(/./, &:capitalize)
#10
4
Most of these answers edit the string in place, when you are just formatting for view output you may not want to be changing the underlying string so you can use tap
after a dup
to get an edited copy
这些答案中的大多数都在适当的地方编辑字符串,当您只是对视图输出进行格式化时,您可能不希望更改底层字符串,以便您可以在一个dup之后使用tap来获取编辑好的副本
'test'.dup.tap { |string| string[0] = string[0].upcase }
#11
3
If and only if OP would want to do monkey patching on String object, then this can be used
如果且仅当OP想要对String对象进行monkey补丁时,则可以使用这个
class String
# Only capitalize first letter of a string
def capitalize_first
self.sub(/\S/, &:upcase)
end
end
Now use it:
现在使用它:
"i live in New York".capitalize_first #=> I live in New York
#12
2
No-one's mentioned gsub, which lets you do this concisely.
没有人提到gsub,它可以让你简洁地做这件事。
string.gsub(/^([a-z])/) { $1.capitalize }
Example:
例子:
> 'caps lock must go'.gsub(/^(.)/) { $1.capitalize }
=> "Caps lock must go"
#13
1
An even shorter version could be:
一个更短的版本可能是:
s = "i'm from New York..."
s[0] = s.capitalize[0]
#14
1
Note that if you need to deal with multi-byte characters, i.e. if you have to internationalize your site, the s[0] = ...
solution won't be adequate. This SO question suggests using the unicode-util gem
注意,如果您需要处理多字节字符,例如,如果您必须国际化您的站点,那么s[0] =…解决方案不会足够。这个问题建议使用unicode-util gem
Ruby 1.9: how can I properly upcase & downcase multibyte strings?
Ruby 1.9:我怎样才能正确地使用upcase & downcase多字节字符串?
EDIT
编辑
Actually an easier way to at least avoid strange string encodings is to just use String#mb_chars:
实际上,至少避免奇怪字符串编码的一个简单方法是使用string #mb_chars:
s = s.mb_chars
s[0] = s.first.upcase
s.to_s
#15
1
Perhaps the easiest way.
也许最简单的方式。
s = "test string"
s[0] = s[0].upcase
# => "Test string"
#16
0
What about classify method on string ?
那么字符串的分类方法呢?
'somESTRIng'.classify
output:
输出:
#rails => 'SomESTRIng'
#17
-3
string = "i'm from New York"
string.split(/\s+/).each{ |word,i| word.capitalize! unless i > 0 }.join(' ')
# => I'm from New York
#1
84
Titleize will capitalise every word. This line feels hefty, but will guarantee that the only letter changed is the first one.
标题化将把每个字都大写。这句话让人感觉很沉重,但可以保证,唯一改变的是第一封信。
new_string = string.slice(0,1).capitalize + string.slice(1..-1)
Update:
更新:
irb(main):001:0> string = "i'm from New York..."
=> "i'm from New York..."
irb(main):002:0> new_string = string.slice(0,1).capitalize + string.slice(1..-1)
=> "I'm from New York..."
#2
111
This should do it:
这应该这样做:
title = "test test"
title[0] = title[0].capitalize
puts title # "Test test"
#3
48
You can use humanize. If you don't need underscores or other capitals in your text lines.
您可以使用人性化。如果你不需要下划线或其他大写字母在你的文本行。
Input:
输入:
"i'm from New_York...".humanize
Output:
输出:
"I'm from new york..."
#4
35
str = "this is a Test"
str.sub(/^./, &:upcase)
# => "This is a Test"
#5
20
As of Rails 5.0.0.beta4 you can use the new String#upcase_first
method or ActiveSupport::Inflector#upcase_first
to do it. Check this blog post for more info.
在Rails 5.0.0。您可以使用新的字符串#upcase_firstmethod或ActiveSupport::Inflector#upcase_first来完成它。查看这篇博文获得更多信息。
#6
14
An object oriented solution:
面向对象的解决方案:
class String
def capitalize_first_char
self.sub(/^(.)/) { $1.capitalize }
end
end
Then you can just do this:
然后你可以这样做:
"i'm from New York".capitalize_first_char
#7
6
Edit 2
I can't seem to replicate your trouble. Go ahead and run this native Ruby script. It generates the exact output your looking for, and Rails supports all of these methods. What sort of inputs are you having trouble with?
我似乎无法再现你的烦恼。继续运行这个原生Ruby脚本。它生成您需要的确切输出,Rails支持所有这些方法。你有什么问题吗?
#!/usr/bin/ruby
def fixlistname(title)
title = title.lstrip
title += '...' unless title =~ /\.{3}$/
title[0] = title[0].capitalize
raise 'Title must start with "You know you..."' unless title =~ /^You know you/
title
end
DATA.each do |title|
puts fixlistname(title)
end
__END__
you know you something WITH dots ...
you know you something WITHOUT the dots
you know you something with LEADING whitespace...
you know you something with whitespace BUT NO DOTS
this generates error because it doesn't start with you know you
output
You know you something WITH dots ...
You know you something WITHOUT the dots...
You know you something with LEADING whitespace...
You know you something with whitespace BUT NO DOTS...
RuntimeError: Title must start with "You know you..."
Edit
Based on your edit, you can try something like this.
根据您的编辑,您可以尝试如下内容。
def fixlistname!
self.title = title.lstrip
self.title += '...' unless title.ends_with?('...')
self.title[0] = title[0].capitalize
errors.add_to_base('Title must start with "You know you..."') unless title.starts_with?("You know you")
end
Original
This will do the trick
这样就可以了
s = "i'm from New York"
s[0] = s[0].capitalize
#=> I'm from New York
When trying to use String#capitalize
on the whole string, you were seeing I'm from new york
because the method:
当你试图用字符串#大写的时候,你会看到我来自纽约,因为这个方法:
Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.
返回第一个字符转换为大写,其余为小写的str副本。
"hello".capitalize #=> "Hello"
"HELLO".capitalize #=> "Hello"
"123ABC".capitalize #=> "123abc"
#8
6
my_string = "hello, World"
my_string.sub(/\S/, &:upcase) # => "Hello, World"
#9
6
str.sub(/./, &:capitalize)
#10
4
Most of these answers edit the string in place, when you are just formatting for view output you may not want to be changing the underlying string so you can use tap
after a dup
to get an edited copy
这些答案中的大多数都在适当的地方编辑字符串,当您只是对视图输出进行格式化时,您可能不希望更改底层字符串,以便您可以在一个dup之后使用tap来获取编辑好的副本
'test'.dup.tap { |string| string[0] = string[0].upcase }
#11
3
If and only if OP would want to do monkey patching on String object, then this can be used
如果且仅当OP想要对String对象进行monkey补丁时,则可以使用这个
class String
# Only capitalize first letter of a string
def capitalize_first
self.sub(/\S/, &:upcase)
end
end
Now use it:
现在使用它:
"i live in New York".capitalize_first #=> I live in New York
#12
2
No-one's mentioned gsub, which lets you do this concisely.
没有人提到gsub,它可以让你简洁地做这件事。
string.gsub(/^([a-z])/) { $1.capitalize }
Example:
例子:
> 'caps lock must go'.gsub(/^(.)/) { $1.capitalize }
=> "Caps lock must go"
#13
1
An even shorter version could be:
一个更短的版本可能是:
s = "i'm from New York..."
s[0] = s.capitalize[0]
#14
1
Note that if you need to deal with multi-byte characters, i.e. if you have to internationalize your site, the s[0] = ...
solution won't be adequate. This SO question suggests using the unicode-util gem
注意,如果您需要处理多字节字符,例如,如果您必须国际化您的站点,那么s[0] =…解决方案不会足够。这个问题建议使用unicode-util gem
Ruby 1.9: how can I properly upcase & downcase multibyte strings?
Ruby 1.9:我怎样才能正确地使用upcase & downcase多字节字符串?
EDIT
编辑
Actually an easier way to at least avoid strange string encodings is to just use String#mb_chars:
实际上,至少避免奇怪字符串编码的一个简单方法是使用string #mb_chars:
s = s.mb_chars
s[0] = s.first.upcase
s.to_s
#15
1
Perhaps the easiest way.
也许最简单的方式。
s = "test string"
s[0] = s[0].upcase
# => "Test string"
#16
0
What about classify method on string ?
那么字符串的分类方法呢?
'somESTRIng'.classify
output:
输出:
#rails => 'SomESTRIng'
#17
-3
string = "i'm from New York"
string.split(/\s+/).each{ |word,i| word.capitalize! unless i > 0 }.join(' ')
# => I'm from New York