string = “this is a String”
string.capitalize = “This is a string”
That works but changes my capital “a String” to lowercase.
I only want to capitalize first letter.
So I try"
string[0…0].capitalize
irb => “T”
OK
string[0…0].capitalize!
irb => “T”
irb string
irb => “this is a string”
I am a noob but I don’t get that.
Where is my capitalised first letter.
I am a noob but I don’t get that.
Where is my capitalised first letter.
What you’ve done is to create a new string, consisting of the single
character ‘t’. Then you’ve done an in-place capitalize on that
string; then you’ve discarded it
I can’t think of a better way to do this than what’s already been
posted, though it really does feel like there should be.
OK
string[0…0].capitalize!
irb => “T”
irb string
irb => “this is a string”
What you’ve done is to create a new string, consisting of the single
character ‘t’. Then you’ve done an in-place capitalize on that
string; then you’ve discarded it
Another not-so-brilliant way to do is to put the created string back to
the original string by doing this:
string[0…0] = string[0…0].upcase
I can’t think of a better way to do this than what’s already been
posted, though it really does feel like there should be.
I love Ruby but this is cumbersome.
There are plenty of situations where people want to
capitalize only the first letter.
By saying:
string[0,1].capitalize! with ! should read like:
Capitalize only the first character within string ‘string’
Or is that stupid thinking.
Its a method on the first character.
I love Ruby but this is cumbersome.
Well, i don’t think this is a Ruby specific behavior. I have just tried
the same thing in Python:
s = “this is a String”
s.capitalize()
‘This is a string’
i.e. it has absolutely the same semantics as in Ruby.
There are plenty of situations where people want to
capitalize only the first letter.
The problem is not the capitalization of the first letter (as this
works), but rather that it turns the other first-letters to lowercase.
I don’t know why the capitalize() function is defined like this - both
in Python and Ruby…
By saying:
string[0,1].capitalize! with ! should read like:
Capitalize only the first character within string ‘string’
What about this:
x = string[0,1]
x.capitalize!
Should this still capitalize only the first character within string
‘string’? I think the answer is obviously no. But your code is
essentially the same, without using the temporary variable x.
It may be cumbersome but the alternative you describe would be worse
Ruby is pretty strict about left-to-right evaluation. This:
string[0,1]
means something: a one-character substring of string. What you do with that substring – what messages you send it – is a completely
separate, subsequent transaction.