Expect errors mixing numbers and strings

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the types category.

Last Updated: 2024-11-23

More specifically: This issue occurs in strongly typed languages like Ruby. The code will "work" in JavaScript, though the conversion of types in the result may surprise you.

I wanted to add the @subject.id to this code to make the file name more unique

First attempt:

zip_file_name = StringUtility.unix_friendly("#{@subject.name.rstrip}#{author ? "-#{author}" : ''}") + @subject.id + '.zip'

This blew up. Why? Because

TypeError: no implicit conversion of Integer into String

in

./app/models/downloaders_and_converters/author_zip_file_creator_service.rb:40:in+'

The fix was to call to_s on the @subject.id first.

zip_file_name = StringUtility.unix_friendly("#{@subject.name.rstrip}#{author ? "-#{author}" : ''}") + @subject.id.to_s + '.zip'

Lesson

In strongly typed languages (e.g. Ruby), adding an integer and a string will cause a failure. This is in contrast to weakly typed language, where this will execute (but sometimes with surprising results)