Pergunta

In rails I am using an integer to represent a user's phone number.

When I get the output from @user.phone_number I get => 4088388579 which is 10 digits and the phone number that was entered.

When I do @user.phone_number.size I get => 8

Why is this doing this?

FYI: I have a validation in the model that verifies that the length is 10 digits. validates :phone_number, :length => {is: 10, :message => "A phone number needs to be 10 digits"}

Foi útil?

Solução

In Ruby like in many languages an Integer (class Fixnum) is formed by 8 bytes in 64-bit machines (4 bytes in 32-bit ones). So the .size method returns the number of bytes that this number represents.

If your number were big enough, like a Long in other languages (class Bignum) it will be formed by 12 bytes (actually it depends of the machine architecture).

To check the length of characters as a literal, you can do: your_number.to_s.size.

For instance:

$ > 0.class
 # => Fixnum 
$ > 0.size 
 # => 8 

$ > 99999999999999999999.class
 # => Bignum 
$ > 99999999999999999999.size
 # => 12
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top