`to_s` isn't converting an integer to a string

Alec Wilson picture Alec Wilson · Feb 26, 2015 · Viewed 18.8k times · Source

I am calling to_s within a method:

$  def my_function(num)
$    number = num.to_s.split(//)
$    puts number
$  end

$  my_function(233)
2
3
3
# => nil

It looks to me like within the function, no array is created since the output is nil. Why is an array of strings not created when to_s.split(//) is called inside a method?

Also, why is the output for puts number seemingly just each digit on its own line? Do I need to explicitly create the array within the function and then explicitly push the split number into it?

Answer

dwenzel picture dwenzel · Feb 26, 2015

When you call puts on an array, it outputs each element of the array separately with a newline after each element. To confirm that your to_s methods are converting the number to a string, try using print instead of puts.

As for the nil that's output, that is the return value of your function. Unless there is an explicit return, the return value of a function will be the evaluation of the last line, which in your case is: puts number. The return value of puts number is nil; printing the value of number is a side effect, not the return value.

I'm curious as to why the output was indeed an array in your first lines of code (not within the function):

$  num = 233
$  number = num.to_s.split(//)
$  puts number
=> ['2', '3', '3']

I suspect that you actually saw that output after the num.to_s.split(//) line, not the puts number line.