C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Here: We convert the string "1234" into an Integer. And we convert a string with floating-point data into a Float.
Then: We add the 2 numbers together. This shows they are no longer strings, which could not be added in this way.
Ruby program that converts strings, numbers
# Two strings with numeric contents.
value1 = "1234"
value2 = "1234.5678"
# Convert strings to numbers.
number1 = Integer(value1)
number2 = Float(value2)
# Print numbers.
print "Number1: ", number1, "\n"
print "Number2: ", number2, "\n"
# Add numbers together.
# ... Could not be done with strings.
number3 = number1 + number2
# Print final number.
print "Number3: ", number3, "\n"
Output
Number1: 1234
Number2: 1234.5678
Number3: 2468.5678
Tip: More advanced mathematical operations are available as methods in the Math class.
Ruby program that uses exponents
# An initial value.
value = 3
# Square the value.
square = value ** 2
# Cube the value.
cube = value ** 3
# Display our results.
puts square
puts cube
Output
9
27
And: If the number is zero, nonzero returns nil. So it returns the number with 0 changed to nil.
Ruby program that uses zero, nonzero
value = 0
if value.zero?
puts "A"
end
if value.nonzero?
puts "B" # Not reached.
end
value = 1
if value.nonzero?
puts "C"
end
Output
A
C
Tip: Using the == operator is superior in most programs. The eql method just adds complexity—1.0 usually should equal 1.
Ruby program that uses eql
value1 = 1
value2 = 1.0
value3 = 1
if value1.eql? value2
puts "A" # Not reached.
end
if value1 == value2
puts "B"
end
if value1.eql? value3
puts "C"
end
Output
B
C