`to_s` isn't converting an integer to a string
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.
Ruby - Convert Integer to String
Or you can convert the integer to its character value:
a[0].chr
How can I convert a string into an integer in RUBY?
To convert string to integer: my_str.to_i
, for example
"foo".to_i # 0
"132".to_i # 132
"132.4".to_i # 132
"foo132".to_i # 0
"132foo".to_i # 132
To find if a string has an odd or even number of characters: my_str.length.odd?
or my_str.length.even?
, for example:
"foo".length.odd? # true
"132".length.odd? # true
"foo".length.even? # false
"132".length.even? # false
SEE ALSO:
to_i
Strictly convert string to integer (or nil)
Use Integer(string)
It will raise an ArgumentError error if the string cannot convert to an integer.
Integer('5abc') #=> ArgumentError: invalid value for Integer(): "5abc"
Integer('5') #=> 5
You'd still need your number_or_nil method if you want the behavior to be that nil is returned when a string cannot be converted.
def number_or_nil(string)
Integer(string || '')
rescue ArgumentError
nil
end
You should be careful to rescue from a particular exception. A bare rescue (such as "rescue nil") will rescue from any error which inherits from StandardError and may interfere with the execution of your program in ways you don't expect. Integer() will raise an ArgumentError, so specify that.
If you'd rather not deal with exceptions and just prefer a shorter version of your number_or_nil you can take advantage of implicit return values and write it as:
def number_or_nil(string)
num = string.to_i
num if num.to_s == string
end
number_or_nil '5' #=> 5
number_or_nil '5abc' #=> nil
This will work the way you expect.
Format integer to string with fixed length in Ruby
How about getting the last three digits using % 1000
instead of doing string manipulations?
[1, 12, 123, 1234].map { |e| format('%03d', e % 1000) }
Update:
As suggested by the Tin Man in the comments, the original version is better in terms of readability and only abount 1.05x slower than this one, so in most cases it probably makes sense to use that.
Convert array of strings to an array of integers
To convert a string to number you have the to_i
method.
To convert an array of strings you need to go through the array items and apply to_i
on them. You can achieve that with map
or map!
methods:
> ["", "22", "14", "18"].map(&:to_i)
# Result: [0, 22, 14, 18]
Since don't want the 0
- just as @Sebastian Palma said in the comment, you will need to use an extra operation to remove the empty strings: (The following is his answer! Vote for his comment instead :D)
> ["", "22", "14", "18"].reject(&:empty?).map(&:to_i)
# Result: [22, 14, 18]
the difference between map
and map!
is that map
will return a new array, while map!
will change the original array.
In Ruby, why do I need to convert an integer into a string to print it?
print
and puts
do not require you to convert a number to a string. In this case, the problem is that you're trying to add a number to a string. This expression:
'I think you really mean ' + newnumber + ' right?'
has to be evaluated before puts
can receive its argument. You can't add numbers to strings, for the reason stated in the error you'll get when you try:
TypeError: no implicit conversion of Fixnum into String
You can do this, though:
puts newnumber
If you want to get implicit type conversion while outputting, use interpolation:
puts "I think you really mean #{newnumber} right?"
Ruby will call to_s
on newnumber
automatically.
Note that you must use "
double-quotes "
around your string, because interpolation won't occur in single-quoted strings.
Related Topics
How to Distribute a Ruby Script via Homebrew
How to Sort So That "Vitamin B12" Is Not in Front of "Vitamin B6"
Restart Rails Server Automatically After Every Change in Controllers
Undefined Method Error When Creating Delayed_Job Workers with Script/Delay_Job
Config Undefined in Environment Specific Configuration Files
Inserting an Array into Every Nth Element of Another
Integrate Shoes into Aptana Studio Radrails
Ruby Dynamically Naming Arrays
Undefined Method 'Email' for Nil:Nilclass in Exibe the Mail of Table Father
Ruby: Why Are All Coordinates Getting Updated in an Array of Arrays
Rails, Ruby, How to Count and Sort, Display Top Results
How to Create Automatically a Instance of Every Class in a Directory
Undefined Method Error When Creating Delayed_Job Workers with Script/Delay_Job
Ruby Multiple Background Threads
How to Install Ruby System-Wide Using Rbenv