things with strings

By | February 28, 2016

RuboCop is a Ruby static code analyzer. Out of the box it will enforce many of the guidelines outlined in the community Ruby Style Guide.

rubo-logo-horizontal

The above links lead to authoritative sources about Rubocop.

I wanted to make a comment about variable types, and one convention Rubocop enforces.

This little program shows how loosely variables in Ruby are typed, and re-typed, so to speak:

#!/usr/bin/env ruby
def number_is (number)
  print number
  puts '------'
  puts "number is String: #{number.is_a?(String)}"
  puts "number is Fixnum: #{number.is_a?(Fixnum)}"
  puts "number is Float: #{number.is_a?(Float)}"
end
number = '500.00'
number_is(number)
number = 500
number_is(number)
number = 500.00
number_is(number)

Produces the following output:

500.00——
number is String: true
number is Fixnum: false
number is Float: false
500——
number is String: false
number is Fixnum: true
number is Float: false
500.0——
number is String: false
number is Fixnum: false
number is Float: true

Process finished with exit code 0

Note that whatever last loaded into the variable “number”, determines number’s variable type – and it can change! Variable type is data-driven.

Somewhat along those lines, string interpolation interprets whatever it is handed as a string representation before presenting it. (Perhaps they should have called it interprolation?)

For example, if the last data loaded to the variable number causes it to become Fixnum or Float, string interpolation will convert it’s output to String before printing it. Interpolation doesn’t change what’s in the variable, it changes how it is represented. The #{} contains the interpolated part.

i.e. print “This is what’s in number: #{number}”

All variables in Ruby are objects, and therefore can have methods attached. For example, you could say:

print “This is what’s in number: #{number.to_s}”

…and thereby force a String conversion of number before interpolation makes a default conversion.

So, what’s the point that ties all this together?

Rubocop, (see above), will throw a style warning if it sees the to_s method used inside of an interpolated string, because it knows that the to_s method is redundant in that place.

Ruby will allow the redundancy, but Rubocop won’t.

So, remember that variable typing is a fluid notion in Ruby. Also, if the default conversion with interpolation doesn’t represent the intended output, other mechanisms can be brought to bear, such as  format and regexp, to control the look of the string output.

i.e. print “This is what’s in number: #{format(‘%.2f’, number)}”

And, as a policy, think twice before arguing with a cop.

Leave a Reply

Your email address will not be published. Required fields are marked *