如何在字符串ruby中仅小写第一个字符

时间:2016-11-22 16:30:58

标签: ruby string

如何用ruby将字符串中的第一个字符小写?我找到的所有现有方法都没有成功。

input "Hello World"
output "hello World"

6 个答案:

答案 0 :(得分:8)

一种方式:

str = "Hello World"
str[0] = str[0].downcase
str #=> "hello World"

答案 1 :(得分:2)

def downcase_first_letter(str)
  str[0].downcase + str[1..-1]
end

puts downcase_first_letter('Hello World') #=> hello World

答案 2 :(得分:1)

str = "Hello World"

str = str[0,1].downcase + str[1..-1] #hello World

当然,您也可以更直接地内联或创建方法。

答案 3 :(得分:1)

我的其他答案修改现有字符串,此技术不会:

str  = "Hello World"
str2 = str.sub(str[0], str[0].downcase)

str  #=> "Hello World"
str2 #=> "hello World"

答案 4 :(得分:0)

string = 'Hello World'

puts string[0].downcase #This will print just the first letter in the lower case.

如果您要打印第一个字符的小写字母,其余的字符串使用此

string = 'Hello World'
newstring = string[0].downcase + string[1..-1]

puts newstring

答案 5 :(得分:0)

最好的答案是:

'foo_bar_baz'.camelize(:lower) =>“ fooBarBaz”

参考:https://makandracards.com/makandra/24050-ruby-how-to-camelize-a-string-with-a-lower-case-first-letter