仅将字符串的第一个字符大写并保留其他字符? (导轨)

发布于 2024-08-29 04:55:41 字数 1450 浏览 4 评论 0原文

我试图让 Rails 将字符串的第一个字符大写,并保留所有其他字符。我遇到了一个问题,“我来自纽约”变成了“我来自纽约”。

我将使用什么方法来选择第一个字符?

谢谢

编辑:我尝试实现 macek 建议的内容,但我收到了“未定义的方法`capitalize'”错误。代码在没有大写行的情况下工作正常。感谢您的帮助!

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

编辑2:让它工作。感谢您的帮助!

编辑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

编辑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

编辑5:这很奇怪。我可以通过使用下面的行来消除未定义的方法错误,问题是它似乎用数字替换了第一个字母,而不是大写y 在 You 中,它将 y 变成 121

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

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

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!

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!

EDIT 3: Wait, no I didn't... Here's what I have in my list model.

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?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

终止放荡 2024-09-05 04:55:41

这应该可以做到:

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

This should do it:

title = "test test"     
title[0] = title[0].capitalize
puts title # "Test test"
佞臣 2024-09-05 04:55:41

Titleize 会将每个单词大写。
这行代码感觉很重,但会保证唯一改变的字母是第一个字母。

new_string = string.slice(0,1).capitalize + string.slice(1..-1)

更新:

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

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..."
╄→承喏 2024-09-05 04:55:41

Rails 开始5.0.0.beta4 您可以使用新的 String#upcase_first 方法或 ActiveSupport::Inflector#upcase_first 来执行此操作。查看此博文了解更多信息信息。

所以

"i'm from New York...".upcase_first

会输出:

"I'm from New York..."

As of Rails 5.0.0.beta4 you can use the new String#upcase_firstmethod or ActiveSupport::Inflector#upcase_first to do it. Check this blog post for more info.

So

"i'm from New York...".upcase_first

Will output:

"I'm from New York..."
琴流音 2024-09-05 04:55:41

您可以使用人性化。
如果您的文本行中不需要下划线或其他大写字母。

输入:

"i'm from New_York...".humanize

输出:

"I'm from new york..."

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..."
深海蓝天 2024-09-05 04:55:41
str = "this is a Test"
str.sub(/^./, &:upcase)
# => "This is a Test"
str = "this is a Test"
str.sub(/^./, &:upcase)
# => "This is a Test"
潦草背影 2024-09-05 04:55:41

面向对象的解决方案:

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

那么你可以这样做:

"i'm from New York".capitalize_first_char

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
乖不如嘢 2024-09-05 04:55:41
str.sub(/./, &:capitalize)
str.sub(/./, &:capitalize)
就是爱搞怪 2024-09-05 04:55:41

编辑2

我似乎无法复制你的麻烦。继续运行这个本机 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

输出

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

编辑

根据您的编辑,您可以尝试类似的操作。

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

原始

这将解决问题

s = "i'm from New York"
s[0] = s[0].capitalize
#=> I'm from New York

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

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

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

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?

#!/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.

"hello".capitalize    #=> "Hello"
"HELLO".capitalize    #=> "Hello"
"123ABC".capitalize   #=> "123abc"
偏爱你一生 2024-09-05 04:55:41
my_string = "hello, World"
my_string.sub(/\S/, &:upcase) # => "Hello, World"
my_string = "hello, World"
my_string.sub(/\S/, &:upcase) # => "Hello, World"
梅倚清风 2024-09-05 04:55:41

没有人提到 gsub,它可以让你简洁地做到这一点。

string.gsub(/^([a-z])/) { $1.capitalize }

例子:

 > 'caps lock must go'.gsub(/^(.)/) { $1.capitalize }
=> "Caps lock must go"

No-one's mentioned gsub, which lets you do this concisely.

string.gsub(/^([a-z])/) { $1.capitalize }

Example:

 > 'caps lock must go'.gsub(/^(.)/) { $1.capitalize }
=> "Caps lock must go"
瑾夏年华 2024-09-05 04:55:41

这些答案中的大多数都在适当的位置编辑字符串,当您只是格式化视图输出时,您可能不想更改底层字符串,因此您可以在 dup 之后使用 tap获取编辑后的副本

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

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

'test'.dup.tap { |string| string[0] = string[0].upcase }
攒一口袋星星 2024-09-05 04:55:41

当且仅当 OP 想要对 String 对象进行猴子修补时,才可以使用

class String
  # Only capitalize first letter of a string
  def capitalize_first
    self.sub(/\S/, &:upcase)
  end
end

现在使用它:

"i live in New York".capitalize_first #=> I live in New York

If and only if OP would want to do monkey patching on String object, then this can be used

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
怼怹恏 2024-09-05 04:55:41

更短的版本可能是:

s = "i'm from New York..."
s[0] = s.capitalize[0]

An even shorter version could be:

s = "i'm from New York..."
s[0] = s.capitalize[0]
为人所爱 2024-09-05 04:55:41

请注意,如果您需要处理多字节字符,即如果您必须国际化您的站点,则 s[0] = ... 解决方案是不够的。这个 Stack Overflow 问题建议使用 unicode-util gem

Ruby 1.9:我怎样才能正确地大写&小写多字节字符串?

编辑

实际上,至少避免奇怪的字符串编码的更简单方法是仅使用 字符串#mb_chars

s = s.mb_chars
s[0] = s.first.upcase
s.to_s

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 Stack Overflow question suggests using the unicode-util gem

Ruby 1.9: how can I properly upcase & downcase multibyte strings?

EDIT

Actually an easier way to at least avoid strange string encodings is to just use String#mb_chars:

s = s.mb_chars
s[0] = s.first.upcase
s.to_s
ゞ花落谁相伴 2024-09-05 04:55:41

从版本 5.2.3 开始,Rails 具有 upcase_first 方法。

例如,"my Test string".upcase_first 将返回我的测试字符串

Rails starting from version 5.2.3 has upcase_first method.

For example, "my Test string".upcase_first will return My Test string.

厌倦 2024-09-05 04:55:41

也许是最简单的方法。

s = "test string"
s[0] = s[0].upcase
# => "Test string"

Perhaps the easiest way.

s = "test string"
s[0] = s[0].upcase
# => "Test string"
情泪▽动烟 2024-09-05 04:55:41
"i'm from New York".camelize
=> "I'm from New York"
"i'm from New York".camelize
=> "I'm from New York"
夕色琉璃 2024-09-05 04:55:41
string = "i'm from New York"
string.split(/\s+/).each{ |word,i| word.capitalize! unless i > 0 }.join(' ')
# => I'm from New York
string = "i'm from New York"
string.split(/\s+/).each{ |word,i| word.capitalize! unless i > 0 }.join(' ')
# => I'm from New York
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文