Skip to content

Instantly share code, notes, and snippets.

@rockBreaker
Created January 11, 2016 17:00
Show Gist options
  • Save rockBreaker/7a87e5249f7beb86daf0 to your computer and use it in GitHub Desktop.
Save rockBreaker/7a87e5249f7beb86daf0 to your computer and use it in GitHub Desktop.
/*
* call-seq:
* str.capitalize! -> str or nil
*
* Modifies <i>str</i> by converting the first character to uppercase and the
* remainder to lowercase. Returns <code>nil</code> if no changes are made.
* Note: case conversion is effective only in ASCII region.
*
* a = "hello"
* a.capitalize! #=> "Hello"
* a #=> "Hello"
* a.capitalize! #=> nil
*/
static VALUE
rb_str_capitalize_bang(VALUE str)
{
rb_encoding *enc;
char *s, *send;
int modify = 0;
unsigned int c;
int n;
str_modify_keep_cr(str);
enc = STR_ENC_GET(str);
rb_str_check_dummy_enc(enc);
if (RSTRING_LEN(str) == 0 || !RSTRING_PTR(str)) return Qnil;
s = RSTRING_PTR(str); send = RSTRING_END(str);
c = rb_enc_codepoint_len(s, send, &n, enc);
if (rb_enc_islower(c, enc)) {
rb_enc_mbcput(rb_enc_toupper(c, enc), s, enc);
modify = 1;
}
s += n;
while (s < send) {
c = rb_enc_codepoint_len(s, send, &n, enc);
if (rb_enc_isupper(c, enc)) {
rb_enc_mbcput(rb_enc_tolower(c, enc), s, enc);
modify = 1;
}
s += n;
}
if (modify) return str;
return Qnil;
}
/*
* call-seq:
* str.capitalize -> new_str
*
* Returns a copy of <i>str</i> with the first character converted to uppercase
* and the remainder to lowercase.
* Note: case conversion is effective only in ASCII region.
*
* "hello".capitalize #=> "Hello"
* "HELLO".capitalize #=> "Hello"
* "123ABC".capitalize #=> "123abc"
*/
static VALUE
rb_str_capitalize(VALUE str)
{
str = rb_str_dup(str);
rb_str_capitalize_bang(str);
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment