Capitalizing a sentence - ruby

Is there a method (perhaps in some library from Rails) or an easy way that capitalizes the first letter of a string without affecting the upper/lower case status of the rest of the string? I want to use it to capitalize error messages. I expect something like this:
"hello iPad" #=> "Hello iPad"

There is a capitalize method in Ruby, but it will downcase the rest of the string. You can write your own otherwise:
class String
def capitalize_first
(slice(0) || '').upcase + (slice(1..-1) || '')
end
def capitalize_first!
replace(capitalize_first)
end
end
Edit: Added capitalize_first! variant.

Rather clumsy, but it works:
str = "hello IiPad"
str[0] = str[0].upcase #or .capitalize

Thanks to other answers, I realized some points that I need to be aware of, and also that there is no built in way. I looked into the source of camelize in Active Support of Rails as hinted by Vitaly Zemlyansky, which gave me a hint: that is to use a regex. I decided to use this:
sub(/./){$&.upcase}

Try this
"hello iPad".camelize

Related

Create a regex that returns an array

I am working in Ruby. I need to create a regex that takes in a string, I suppose, and returns an array with only the words that start with "un" and end with "ing". I have no clue how to do it :/
def words_starting_with_un_and_ending_with_ing(text)
!!text.capitalize.scan(/\A+UN\Z+ING/)
end
Something like this:
def uning string
string.scan(/\b[Uu]n[a-z]*ing\b/)
end
See String#scan for more info. For a nice interactive introduction to Regex take a look at RegexOne.

Elegantly put strings in same line

I need to puts a string like
puts "#{movie.title}, #{movie.imdb_rating.round(3)}, #{movie.imdb_ratings_count}"
So the output will be Gone Girl, 8.23, 302532
However, these are quite tedious since I always need to add #{} and "",
What is a good way to quick puts, without always adding #{} and ""?
I suggest constructing an array and using the join method.
def printStrings do *strings
strings.join(', ')
end
printStrings 'apple', 'banana', 'orange' #'apple, banana, orange'
Alternatively, you can utilize a special variable, called the output field separator, which you can access as $,. (Its default value is nil)
$, = ', '
print 'apple', 'banana', 'orange' #'apple, banana, orange'
$, = nil
This method is outlined in the docs for print
It would make sense to add a method to the Movie class:
class Movie
def to_desc
"##title, #{#imdb_rating.round(3)}, ##imdb_ratings_count"
end
end
LukeP's answer is good if you want the same punctuation between each value but if you want something with a varying format, eg Gone Girl - 8.23, 302532, you can use ruby's % operator for string formating:
"%s - %s, %s" % [movie.title, movie.imdb_rating.round(3), movie.imdb_ratings_count]
Ruby's printing is solid but not amazing. Have you looked at the Awesome Print gem?
https://github.com/michaeldv/awesome_print
It's what I use to do elegant printing. It's a little unclear exactly how you're asking to format it, but this gems seems like it'll give you enough options to solve your problem.

how to change values between tags in a string

If I have the following string:
str="hello %%one_boy%%'s something %%four_girl%%'s something more"
how would I edit it to get the following output from printing str:
"hello ONE_BOY's something FOUR_GIRL's something more"
I have been trying to use 'gsub' and 'upcase' methods but am struggling with the regex to get each word between my '%%' symbols.
ruby-1.9.2-p136 :066 > str.gsub(/%%([^%]+)%%/) {|m| $1.upcase}
=> "hello ONE_BOY's something FOUR_GIRL's something more"
The [^%]+ says it will match 1 or more characters except %, and the $1is a global variable that stores the back reference to what was matched.
s.gsub(/%%([^%]+)%%/) { $1.upcase }
Here's a quick and dirty way:
"hello %%one_boy%%'s something %%four_girl%%'s something more".gsub(/(%%.*?%%)/) do |x|
x[2 .. (x.length-3)].upcase
end
The x[2 .. (x.length-3)] bit slices out the middle of the match (i.e. strips off the leading and trailing two characters).
If you're able to choose the delimiters, you might be able to use String.interpolate from the Facets gem:
one_boy = "hello".upcase
str = "\#{one_boy}!!!"
String.interpolate{ str } #=> "HELLO!!!"
But I'd first check that Facets doesn't cause any conflicts with Rails.
str.gsub(/%%([^%]+)%%/) { |match| $1.upcase }

Capitalization of strings

Let us imagine, that we have a simple abstract input form, whose aim is accepting some string, which could consist of any characters.
string = "mystical characters"
We need to process this string by making first character uppercased. Yes, that is our main goal. Thereafter we need to display this converted string in some abstract view template. So, the question is: do we really need to check whether the first character is already written correctly (uppercased) or we are able to write just this?
theresult = string.capitalize
=> "Mystical characters"
Which approach is better: check and then capitalize (if need) or force capitalization?
Check first if you need to process something, because String#capitalize doesn't only convert the first character to uppercase, but it also converts all other characters downcase. So..
"First Lastname".capitalize == "First lastname"
That might not be the wanted result.
If I understood correctly you are going to capitalize the string anyway, so why bother checking if it's already capitalized?
Based on Tonttu answer I would suggest not to worry too much and just capitalize like this:
new_string = string[0...1].capitalize + string[1..-1]
I ran in to Tonttu's problem importing a bunch of names, I went with:
strs = "first lastname".split(" ")
return_string = ""
strs.each do |str|
return_string += "#{str[0].upcase}#{str[1..str.length].downcase} "
end
return_string.chop
EDIT: The inevitable refactor (over a year) later.
"first lastname".split(" ").map do |str|
"#{str[0].upcase}#{str[1..str.length].downcase}"
end.join(' ')
while definitely not easier to read, it gets the same result while declaring fewer temporary variables.
I guess you could write something like:
string.capitalize unless string =~ /^[A-Z].*/
Personally I would just do string.capitalize
Unless you have a flag to be set for capitalized strings which you going to check than just capitalize without checking.
Also the capitalization itself is probably performing some checking.

English Sentence to Camel-cased method name

I had to convert a series of sentences into camel-cased method names. I ended writing something for it. I am still curious if there's something simpler for it.
Given the string a = "This is a test." output thisIsATest
I used for following:
a.downcase.gsub(/\s\w/){|b| b[-1,1].upcase }
Not sure it's better as your solution but it should do the trick:
>> "This is a test.".titleize.split(" ").join.camelize(:lower)
=> "thisIsATest."
titleize: uppercase every first letter of each word
split(" ").join: create an array with each word and join to squeeze the spaces out
camelize(:lower): make the first letter lowercase
You can find some more fun functions in the Rails docs: http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html
"active_record".camelize(:lower)
output : "activeRecord"
use these
"Some string for you".gsub(/\s+/,'_').camelize(:lower) #=> "someStringForYou"
gsub: Replace spaces by underscores
camelize: java-like method camelcase
You might try using the 'English' gem, available at http://english.rubyforge.org/
require 'english/case'
a = "This is a test."
a.camelcase().uncapitalize() # => 'thisIsATest

Resources