Elegantly put strings in same line - ruby

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.

Related

Replace characters from string Ruby

I have the following string which has an array element in it and I will like to remove the quotes in the array element to the outside of the array:
"date":"2014-05-04","name":"John","products":["12","14","45"],"status":"completed"
Is there a way to remove the double quotes in [] and add double quotes to the start and end of []? Results:
"date":"2014-05-04","name":"John","products":"[12,14,45]","status":"completed"
Can that be done in ruby or is there a command line that I can use?
Your string looks like a json hash to me:
json = '{"date":"2014-05-04","name":"John","products":["12","14","45"],"status":"completed"}'
require 'json'
hash = JSON.load(json)
hash.update('products' => hash['products'].map(&:to_i))
puts hash.to_json
# => {"date":"2014-05-04","name":"John","products":[12,14,45],"status":"completed"}
Or if you really want to have the array represented as a string (what is not json anymore):
hash.update('products' => hash['products'].map(&:to_i).to_s) # note .to_s here
puts hash.to_json
# => {"date":"2014-05-04","name":"John","products":"[12,14,45]","status":"completed"}
The answer by #spickermann is pretty good, and the best way I can think of, but since I had fun trying to find an alternative without using json, here it goes:
def string_to_result(str)
str.match(/(?:\[)((?:")+(.)+(?:")+)+(?:\])/)
str.gsub($1, "#{$1.split(',').map{ |num| num.gsub('"', '') }.join(',')}").gsub(/\[/, '"[').gsub(/\]/, ']"').gsub(/String/, 'Results')
end
Is ugly as hell, but it works :P
I tried to do it on a single step, but that was way harder for my regexp skills.
Anyway, you should never parse something structured such as json or xml using only regexps, and this is merely for fun.
[EDIT] Had the bracket adjacent quotes wrong,sorry. Fixed.
Also, one more thing, this fails A LOT! An empty array or an array in other place in the string are just a few cases where it would fail.
You could use the form of String#gsub that takes a block:
str = '"2014-05-04","name":"John","products":["12","14","45"],"status":"completed"'
puts str.gsub(/\["(\d+)","(\d+)","(\d+)"\]/) { "\"[#{$1},#{$2},#{$3}]\"" }
#"2014-05-04","name":"John","products":"[12,14,45]","status":"completed"

Capitalizing a sentence

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

how can i consolidate this expression?

I'm removing the initial "The" and spaces of band names for concatenating into a url.
I have this, but it's ugly and I'd like to consolidate into one expression.
#artist.sub!(/[Tt]he/, '')
#artist.gsub!(/\s+/, '')
Try:
#artist.gsub!(/(\A[Tt]he)|(\s+)/, '')
You can of course chain #sub and #gsub expressions; e.g.,
#artist = #artist.sub(/^[Tt]he/, '').gsub(/\s+/, '')
Any more compact and I would hesitate to call it elegant—just clever (and unclear).
Note the use of #sub and #gsub instead of #sub! and #gsub!. Per #pguardiario's comment, the second two will return nil if there is no match, causing a NoMethodError exception. Also, note that this has an anchor to prevent "The" from being removed from the middle of the string.
If you're trying to create a slug for use in URLs, you might be better going with a method in a library.
I'd go with:
#artist = #artist.sub(/\Athe\b/i, '').strip

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