Ruby-on-rails 仅将字符串的第一个字符大写而其他字符不理会?(导轨)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2646709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:31:57  来源:igfitidea点击:

Capitalize only first character of string and leave others alone? (Rails)

ruby-on-railsstringcapitalization

提问by Daniel O'Connor

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 的编辑,但仍然得到一个未定义的方法 `capitalize'"错误。我做错了什么?

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 yin You, it turns the yinto a 121

编辑 5:这很奇怪。我可以通过使用下面的行来摆脱未定义的方法错误。问题是它似乎用数字替换了第一个字母。例如,而不是资本的Ÿ,它把Ÿ为121

self.title[0] = title[0].to_s.capitalize

采纳答案by Taryn East

Titleize will capitalise every word. This line feels hefty, but will guarantee that the only letter changed is the first one.

Titleize 将大写每个单词。这条线感觉很重,但可以保证唯一改变的字母是第一个。

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..."

回答by Pascal Van Hecke

This should do it:

这应该这样做:

title = "test test"     
title[0] = title[0].capitalize
puts title # "Test test"

回答by Bartuzz

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..."

回答by Lasse Bunk

str = "this is a Test"
str.sub(/^./, &:upcase)
# => "This is a Test"

回答by user1519240

As of Rails 5.0.0.beta4you can use the new String#upcase_firstmethod or ActiveSupport::Inflector#upcase_firstto do it. Check this blog postfor more info.

Rails 5.0.0.beta4 开始,您可以使用新String#upcase_first方法或ActiveSupport::Inflector#upcase_first这样做。查看此博客文章了解更多信息。

回答by lmanners

An object oriented solution:

面向对象的解决方案:

class String
  def capitalize_first_char
    self.sub(/^(.)/) { .capitalize }
  end
end

Then you can just do this:

然后你可以这样做:

"i'm from New York".capitalize_first_char

回答by emlai

str.sub(/./, &:capitalize)

回答by Pavel Pravosud

my_string = "hello, World"
my_string.sub(/\S/, &:upcase) # => "Hello, World"

回答by ma?ek

Edit 2

编辑 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#capitalizeon the whole string, you were seeing I'm from new yorkbecause the method:

尝试String#capitalize在整个字符串上使用时,您看到的I'm from new york是因为该方法:

Returns a copy of strwith the first character converted to uppercase and the remainder to lowercase.

返回str的副本,其中第一个字符转换为大写,其余字符转换为小写。

"hello".capitalize    #=> "Hello"
"HELLO".capitalize    #=> "Hello"
"123ABC".capitalize   #=> "123abc"

回答by Paul.s

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 tapafter a dupto get an edited copy

这些答案中的大多数就地编辑字符串,当您只是格式化视图输出时,您可能不想更改基础字符串,因此您可以tap在 a 之后使用dup来获取编辑后的副本

'test'.dup.tap { |string| string[0] = string[0].upcase }