How do I convert array of numerics to an integer? - ruby

I am trying to convert the following array:
2.0.0-p0 :021 > test = 1, 440, 840
=> [1, 440, 840]
to the following integer:
1440840
If I do a split(',') and then join them, it works, but I'm sure there is a better way.

No need to use split if it's an Array. Just do:
test.join.to_i
Sample run with join:
2.0.0-p195 :007 > t.is_a? Array
=> true
2.0.0-p195 :008 > t.join.to_i
=> 1440840
2.0.0-p195 :009 >

How about
test.inject { |ttl, n| ttl * 1000 + n }

Here are some things to meditate on:
STRING = '1,440,840'
STRING.gsub(',', '').to_i # => 1440840
STRING.tr(',', '').to_i # => 1440840
STRING.delete(',').to_i # => 1440840
STRING.scan(/\d+/).join.to_i # => 1440840
require 'scanf'
STRING.scanf('%d,%d,%d').join.to_i # => 1440840
We don't see scanf used much in Ruby, but it's a mainstay in C, and used often in Perl. It's the opposite side of Kernels's printf, sprintf, format and String's %.

Related

what is [-1, 1] in this ruby code?

I am looking at an example of code and confused.
def self.type(input)
input.strip!
return 'question' if input[-1,1] == '?'
end
So, input[-1] makes sense, it is checking if the last character is a question mark. What does the 1 do? Also, all the example tests pass without the 1.
input[-1,1] means reading 1 character from the last character. It gives the same result as input[-1] because you are reading just 1 character from the last character.
Look at some examples to understand more:
❯ irb
2.3.0 :001 > input = 'lenin'
=> "lenin"
2.3.0 :002 > input[-1]
=> "n"
2.3.0 :003 > input[-1,1]
=> "n"
2.3.0 :004 > input[-2]
=> "i"
2.3.0 :005 > input[-2, 1]
=> "i"
2.3.0 :006 > input[-2, 2]
=> "in"
2.3.0 :007 > input[-2, 3]
=> "in"

Why a dangerous method doesn't work with a character element of String in Ruby?

When I apply the upcase! method I get:
a="hello"
a.upcase!
a # Shows "HELLO"
But in this other case:
b="hello"
b[0].upcase!
b[0] # Shows h
b # Shows hello
I don't understand why the upcase! applied to b[0] doesn't have any efect.
b[0] returns a new String every time. Check out the object id:
b = 'hello'
# => "hello"
b[0].object_id
# => 1640520
b[0].object_id
# => 25290780
b[0].object_id
# => 24940620
When you are selecting an individual character in a string, you're not referencing the specific character, you're calling a accessor/mutator function which performs the evaluation:
2.0.0-p643 :001 > hello = "ruby"
=> "ruby"
2.0.0-p643 :002 > hello[0] = "R"
=> "R"
2.0.0-p643 :003 > hello
=> "Ruby"
In the case when you run a dangerous method, the value is requested by the accessor, then it's manipulated and the new variable is updated, but because there is no longer a connection between the character and the string, it will not update the reference.
2.0.0-p643 :004 > hello = "ruby"
=> "ruby"
2.0.0-p643 :005 > hello[0].upcase!
=> "R"
2.0.0-p643 :006 > hello
=> "ruby"

How do I compare a range to an array?

How do I see if an array matches a range?
[1..3] == [1,2,3] # => false
I've also tried
[1..3].to_a == [1,2,3] # => false
but I'm stumped. Is there any way to coerce a range into an array so I can compare it with one?
ah! Turns out I was getting confused on the syntax.
arr = [1..3] # Actually sets an array with a range as the first element
arr[0] # => 1..3
What I needed was this:
(1..3).to_a == [1,2,3] # => true
2.1.1 :006 > [1..3].class
=> Array
2.1.1 :007 > (1..3).class
=> Range
2.1.1 :008 > (1..3).to_a == [1,2,3]
=> true
hope that solves your issue

Finding out variable class and difference between Hash and Array

Is it possible to clearly identify a class of variable?
something like:
#users.who_r_u? #=>Class (some information)
#packs.who_r_u? #=> Array (some information)
etc.
Can someone provide clear short explanation of difference between Class, Hash, Array, Associated Array, etc. ?
You can use:
#users.class
Test it in irb:
1.9.3p0 :001 > 1.class
=> Fixnum
1.9.3p0 :002 > "1".class
=> String
1.9.3p0 :003 > [1].class
=> Array
1.9.3p0 :004 > {:a => 1}.class
=> Hash
1.9.3p0 :005 > (1..10).class
=> Range
Or:
1.9.3p0 :010 > class User
1.9.3p0 :011?> end
=> nil
1.9.3p0 :012 > #user = User.new
=> #<User:0x0000010111bfc8>
1.9.3p0 :013 > #user.class
=> User
These were only quick irb examples, hope it's enough to see the use of .class in ruby.
You could also use kind_of? to test wheter its receiver is a class, an array or anything else.
#users.kind_of?(Array) # => true
You can find these methods in Ruby document http://ruby-doc.org/core-1.9.3/Object.html
#user.class => User
#user.is_a?(User) => true
#user.kind_of?(User) => true
found helpful: <%= debug #users %>
A difference between Class and Hash? They are too different to even provide normal answer. Hash is basically an array with unique keys, where each key has its associated value. That's why it's also called associative array.
Here is some explanation:
array = [1,2,3,4]
array[0] # => 1
array[-1] # => 4
array[0..2] # => [1,2,3]
array.size # => 4
Check out more Array methods here: http://ruby-doc.org/core-1.9.3/Array.html
hash = {:foo => 1, :bar => 34, :baz => 22}
hash[:foo] # => 1
hash[:bar] # => 34
hash.keys # => [:baz,:foo,:bar]
hash.values # => [34,22,1]
hash.merge :foo => 3921
hash # => {:bar => 34,:foo => 3921,:baz => 22 }
Hash never keeps order of the elments you added to it, it just preserves uniqueness of keys, so you can easily retreive values.
However, if you do this:
hash.merge "foo" => 12
you will get
hash # => {:bar => 34, baz => 22, "foo" => 12, :foo => 2}
It created new key-value pair since :foo.eql? "foo" returns false.
For more Hash methods check out this: http://www.ruby-doc.org/core-1.9.3/Hash.html
Class object is a bit too complex to explain in short, but if you want to learn more about it, reffer to some online tutorials.
And remember, API is your friend.

What are values mapped to?

I don't understand how Ruby hashes work.
I expect these:
a = 'a'
{a => 1}[a] # => 1
{a: 1}[:a] # => 1
{2 => 1}[2] # => 1
How does this work?
{'a' => 1}['a'] # => 1
The first string 'a' is not the same object as the second string 'a'.
Ruby doesn't use object equality (equal?) for comparing hash keys. It wouldn't be very useful if it did after all.
Instead it uses eql?, which for strings is the same as ==
As a footnote to other answers, you can let a hash behave like you expected:
h = {'a'=> 1}
p h['a'] #=> 1
h.compare_by_identity
p h['a'] #=> nil ; not the same object
some_hash[k] = v
Basically, when you do this, what is stored is not a direct association k => v. Instead of that, k is asked for a hash code, which is then used to map to v.
Equal values yield equal hash codes. That's why your last example works the way it does.
A couple of examples:
1.9.3p0 :001 > s = 'string'
=> "string"
1.9.3p0 :002 > 'string'.hash
=> -895223107629439507
1.9.3p0 :003 > 'string'.hash == s.hash
=> true
1.9.3p0 :004 > 2.hash
=> 2271355725836199018
1.9.3p0 :005 > nil.hash
=> 2199521878082658865

Resources