Calling the method `to_i` in Ruby - ruby

Following is my Ruby code:
"100".to_i(9) # => 81
Can somebody explain why the result is 81?

Look into radix and the String#to_i documentation. It's the base. Normal numbers are base 10. You specified base 9.

Related

Ruby: difference between hexencode and hexdigest

Today I read the documentation on Rubies hexdigest method, e.g.
Digest::SHA256.hexdigest('123')
=> "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3"
The documentation says:
Returns the hex-encoded hash value of a given string. This is almost equivalent to Digest.hexencode(Digest::Class.new(*parameters).digest(string)).
Highlighting is by me: What does almost mean here? How is it different?
Of course my example string above yields the same result:
Digest.hexencode(Digest::SHA256.digest('123'))
=> "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3"
Can anyone point me to the cases where the result can be different? I want to understand whether the "almost" points to an important difference or if the difference is irrelevant for me.
As in the module Digest::Instance described hexdigest(string) return hexencode_str_new(value);. In the module Digest described hexencode(string) return hexencode_str_new(value); too. So, there are no differences if use same instance type. "almost" because in the documentation example can be Digest::SHA512 or other.

What does the .size on number mean in ruby?

Why is my ruby giving incorrect size of number? It doesn't matter what's the number. The output is always 4 for the size. What does that mean? I always thought it should give the number of digits.
number = 14
print number
print "\n"
print number.size
output:
14
4
ruby version
ruby 2.1.8p440 (2015-12-16 revision 53160) [i386-mingw32]
I always suggest to check the method you're not sure about using the following scheme:
Check where the method comes from (using Object#method):
number.method(:size)
#=> #<Method: Fixnum#size>
Open docs and learn what it does for Fixnum#size and how it works.
2.1 If you're using IRB, you can run help 'Fixnum#size' to get the docs right in your console
2.2 If you're using pry, you can go with show-doc Fixnum#size (install pry-doc gem first)
In Ruby 2.1.8 method was defined in Fixnum#size.
Starting from Ruby 2.4 it's defined in
Integer#size:
Returns the number of bytes in the machine representation of int.
You are confusing the two methods String#size:
Returns the character length of str.
and Fixnum#size:
Returns the number of bytes in the machine representation of fix.
14 is an object of class Fixnum, so when you call size on it you are getting the number of bytes in the machine representation of the number.
If you would like to know how many digits there are in a number, you can simply convert it to a string first and then call size on that:
14.to_s
# => "14"
14.to_s.size
#=> 2
12345.to_s.size
#=> 5

How to get nth root of a number in Ruby?

For example
x ** 3 # => 125
Knowing that the result of applying ** with an argument 3 to x is 125, how can I get the value of x?
Is there some kind of built-in method for this? I have been looking at the Math module but didn't find anything similar.
Using ** with 1/3:
125 ** (1.0/3)
# => 4.999999999999999
You could also try as below :
irb(main):005:0> 125**(3**-1)
=> 5
irb(main):006:0> 125**(3**-1.0)
=> 4.999999999999999
irb(main):007:0>
update
C:\Users >ruby -v
ruby 1.9.3p448 (2013-06-27) [i386-mingw32]
You can do an Nth root by raising to a fractional power. For example, the 4th root of 625 is 5.
(BigDecimal.new(625)**(1.0/4.0)).to_f
# => 5.0
Note, the .to_f is added for readability in this answer only. Don't cast it to a Float in your code unless you need to. IMHO, BigDecimals are "better" than Floats in Ruby - Floats lose precision too easily and you won't get accurate results. Case in point the accepted awnser above. The cube root of 125 is not 4.99999(repeat). It is 5.0 exactly.
Edit: the Ruby Class Rational seems to handle nth roots a little better.
2.3.3 :007 > 625.to_r ** 0.25
=> 5.0
But it still isn't as precise with a number that produces an irrational root.
2.3.3 :024 > (999.to_r ** 0.25) ** 4
=> 998.9999999999999
Close...but you should be able to get back to 999.0 exactly. My Mac's calculator and excel can do it. Main point - just be careful. If precision is important, Ruby may not handle this exactly the way one would expect.

Error in rounding off values using .round in Ruby

The following piece of code works perfectly in script/console but returns the following error when i compile the same in a ruby script.:
:in `round': wrong number of arguments (1 for 0) (ArgumentError)
tf={"ph"=>{0=>1.33333333333333, 1=>1.5}, "fee"=>{0=>1.66666666666667}, "test"=>{0=>1.16666666666667, 1=>1.25}, "what"=>{0=>2.0, 1=>2.0}, "for"=>{0=>1.5}, "is"=>{0=>1.83333333333333, 1=>1.75}}
tf.each{|k,v| v.each{|k1,v1| tf[k][k1]=(v1.round(5))}}
Any Ideas ? Cheers !
Float#round seems to work differently in Ruby 1.8 and Ruby 1.9: in 1.8 it complains about the given argument, in 1.9 returns back float properly rounded to the given number of decimals.
But, as the article linked in the other answer wisely says:
you should consider the reason you’re
performing the rounding (or
equivalent) operation. If it’s for
presentation reasons only a better way
might be to use a format string
instead, and leave the original data
intact.
From what it looks like, you are not supposed to pass an argument to the round method. You have passed 5 to it.
If you are trying to round it to 5 decimal places, there is no builtin method for that (that I'm aware of). This is a page that explains how to do so: http://solutions.hans-eric.com/rounding-off-floating-point-numbers-in-ruby

How does ruby's String .hash method work?

I'm just a newbie to ruby. I've seen a string method (String).hash .
For example, in irb, I've tried
>> "mgpyone".hash
returns
=> 144611910
how does this method works ?
The hash method is defined for all objects. See documentation:
Generates a Fixnum hash value for this
object. This function must have the
property that a.eql?(b) implies a.hash == b.hash.
The hash value is used by class Hash. Any hash value that
exceeds the capacity of a Fixnum will
be truncated before being used.
So the String.hash method is defined in C-Code. Basically (over-simplified) it just sums up the characters in that string.
If you need to get a consistent hashing output I would recommend NOT to use 'string.hash but instead consider using Digest::MD5 which will be safe in multi-instance cloud applications for example you can test this as mentioned in comment in previous by #BenCrowell
Run this 2x from your terminal, you will get different output each time:
ruby -e "puts 'a'.hash"
But if you run this the output will be consistent:
ruby -e "require 'digest'; puts Digest::MD5.hexdigest 'a'"

Resources