Ruby

Hash

def **check_sqrt**(a, cache)
*# See if the cache contains a square root for this argument.*
if cache.key?(a)
return cache[a]
end
*# Compute square root and memoize it.*
cache[a] = Math.sqrt(a)
return cache[a]
end
*# Use memoize square root method with Hash.*
cache = Hash.new()
puts **check_sqrt**(*9*, cache)
puts **check_sqrt**(*9*, cache)3.0
3.0

number = *1.1*
puts number
*# Use floor to remove the fractional part.*
result1 = number.**floor**
puts result1
*# Use ceil to move to the next highest integer.*
result2 = number.**ceil**
puts result2*1.1*
1
2

number = *1.99*
puts number
*# Truncate removes the fractional part.*
result = number.**truncate**
puts result
*# Negative numbers can be truncated too.*
number = *-1.99*
puts number.**truncate**1.99
1
-1

number_a = 1.234
number_b = -1.234
number_c = 1.99
number_d = -1.99
puts *":::ROUND number_a, number_b :::"*
*# Use round method.*
puts number_a.**round**
puts number_b.**round**
puts *":::ROUND number_c, number_d :::"*
*# The nearest integer is returned.*
puts number_c.**round**
puts number_d.**round**:::ROUND number_a, number_b :::
1
-1
:::ROUND number_c, number_d :::
2
-2

Fibonacci

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

This page was last updated on Sep 14, 2022 (grammar).