Ruby - function changes hash but not integer variable - ruby

I have a function that takes in some parameters including a hash and an integer variable and adjusts their value. The function alters the value of the hash to be used again, however the integer variable resets itself. I believe it's because it's altering a copy of that variable, but I wanted to know how I can change it fully. I've been reading things about proc's but unfortunately I can't seem to solve my issue.
My code is below:
def buyProducts(product, amount, balance, foods, myProducts)
totalPrice = foods[product] * amount
balance -= totalPrice
myProducts[product] = amount
puts "You bought some #{product}\n"
puts "Your remaining balance is $#{balance}\n"
puts "Your current inventory is #{myProducts}"
end
Here, myProducts is a hash which updates each time. balance however is not, thats set as 100 from the start. while the line "your remaining balance" does update, when the function is called again it resets to 100.
I appreciate this is a simple question but any help would be gratefully received!

Here's the key difference: you reassign [the local variable] balance, but not myProducts. Instead, you simply change state of myProducts. That's why these changes "survive" across invocations of the method: the object is the same, it just holds different content.
This is not possible with integers, because each integer is its own object and doesn't have any mutable state.
Your method will have to communicate the changes to the external state by, for example, returning new value of balance (it will then be the caller's responsibility to track/apply the new value). Or you could set an instance variable.

Related

Ruby object variables and why they always equal the same name?

In the books I'm reading, I always see
def initialize (side_length)
#side_length = side_length
end
If the object variable always equals the variable with the same name why not write the language to just equal it without having to type it out?
For example:
def initialize (side_length)
#side_length # this could just equal side_length without stating it
end
That way we don't have to type it over with over.
In the example given:
def initialize(side_length)
#side_length = side_length
end
The #side_length = side_length is just an assignment, passing the available argument to an instance variable, in this case it happens to be the same name as the argument.
However those two values don't have to have same names - it's usually named that way for readability/convention reasons. That same code could just as easily be:
def initialize(side_length)
#muffin = side_length
end
The above code is perfectly fine, it just wouldn't read as well (and might slightly confuse someone giving it a first glance). Here's another example of the argument not being assigned to an instance variable of the same name.
It would be possible to write the language in a way which assumes that the argument variable should automatically be assigned to an instance variable of the same name, but that would mean more logic for handling arguments, and that same assumption may result in more restrictions for the developer, for example, someone who may actually want to assign side_length to #muffin for whatever reason.
Here's a SO question similar to this one - the accepted answer provides an interesting solution.
Hope this helps!
It is because "the object variable [does not] always [equal] the variable withthe [sic] same name".

Why can't I overwrite self in the Integer class?

I want to be able to write number.incr, like so:
num = 1; num.incr; num
#=> 2
The error I'm seeing states:
Can't change the value of self
If that's true, how do bang! methods work?
You cannot change the value of self
An object is a class pointer and a set of instance methods (note that this link is an old version of Ruby, because its dramatically simpler, and thus better for explanatory purposes).
"Pointing" at an object means you have a variable which stores the object's location in memory. Then to do anything with the object, you first go to the location in memory (we might say "follow the pointer") to get the object, and then do the thing (e.g. invoke a method, set an ivar).
All Ruby code everywhere is executing in the context of some object. This is where your instance variables get saved, it's where Ruby looks for methods that don't have a receiver (e.g. $stdout is the receiver in $stdout.puts "hi", and the current object is the receiver in puts "hi"). Sometimes you need to do something with the current object. The way to work with objects is through variables, but what variable points at the current object? There isn't one. To fill this need, the keyword self is provided.
self acts like a variable in that it points at the location of the current object. But it is not like a variable, because you can't assign it new value. If you could, the code after that point would suddenly be operating on a different object, which is confusing and has no benefits over just using a variable.
Also remember that the object is tracked by variables which store memory addresses. What is self = 2 supposed to mean? Does it only mean that the current code operates as if it were invoked 2? Or does it mean that all variables pointing at the old object now have their values updated to point at the new one? It isn't really clear, but the former unnecessarily introduces an identity crisis, and the latter is prohibitively expensive and introduce situations where it's unclear what is correct (I'll go into that a bit more below).
You cannot mutate Fixnums
Some objects are special at the C level in Ruby (false, true, nil, fixnums, and symbols).
Variables pointing at them don't actually store a memory location. Instead, the address itself stores the type and identity of the object. Wherever it matters, Ruby checks to see if it's a special object (e.g. when looking up an instance variable), and then extracts the value from it.
So there isn't a spot in memory where the object 123 is stored. Which means self contains the idea of Fixnum 123 rather than a memory address like usual. As with variables, it will get checked for and handled specially when necessary.
Because of this, you cannot mutate the object itself (though it appears they keep a special global variable to allow you to set instance variables on things like Symbols).
Why are they doing all of this? To improve performance, I assume. A number stored in a register is just a series of bits (typically 32 or 64), which means there are hardware instructions for things like addition and multiplication. That is to say the ALU, is wired to perform these operations in a single clock cycle, rather than writing the algorithms with software, which would take many orders of magnitude longer. By storing them like this, they avoid the cost of storing and looking the object in memory, and they gain the advantage that they can directly add the two pointers using hardware. Note, however, that there are still some additional costs in Ruby, that you don't have in C (e.g. checking for overflow and converting result to Bignum).
Bang methods
You can put a bang at the end of any method. It doesn't require the object to change, it's just that people usually try to warn you when you're doing something that could have unexpected side-effects.
class C
def initialize(val)
#val = val # => 12
end # => :initialize
def bang_method!
"My val is: #{#val}" # => "My val is: 12"
end # => :bang_method!
end # => :bang_method!
c = C.new 12 # => #<C:0x007fdac48a7428 #val=12>
c.bang_method! # => "My val is: 12"
c # => #<C:0x007fdac48a7428 #val=12>
Also, there are no bang methods on integers, It wouldn't fit with the paradigm
Fixnum.instance_methods.grep(/!$/) # => [:!]
# Okay, there's one, but it's actually a boolean negation
1.! # => false
# And it's not a Fixnum method, it's an inherited boolean operator
1.method(:!).owner # => BasicObject
# In really, you call it this way, the interpreter translates it
!1 # => false
Alternatives
Make a wrapper object: I'm not going to advocate this one, but it's the closest to what you're trying to do. Basically create your own class, which is mutable, and then make it look like an integer. There's a great blog post walking through this at http://blog.rubybestpractices.com/posts/rklemme/019-Complete_Numeric_Class.html it will get you 95% of the way there
Don't depend directly on the value of a Fixnum: I can't give better advice than this without knowing what you're trying to do / why you feel this is a need.
Also, you should show your code when you ask questions like this. I misunderstood how you were approaching it for a long time.
It's simply impossible to change self to another object. self is the receiver of the message send. There can be only one.
If that's true, how do bang! methods work?
The bang (!) is simply part of the method name. It has absolutely no special meaning whatsoever. It is a convention among Ruby programmers to name surprising variants of less surprising methods with a bang, but that's just that: a convention.

Why does the rand() return always the same number?

I am using
rand(200)
in my Rails application.
When I run it in console it always returns random number, but if I use it in application line:
index = rand(200)
index is always the same number.
Why is that and how to overcome this?
Simple pseudo-random number generators actually generate a fixed sequence of numbers. The particular sequence you get is determined by the initial "seed" value. My suspicion is that you are always getting the first number in the same sequence. Therefore I suggest we try to change the sequence by calling srand every time before calling rand, thus changing the seed value every time. The docs explain that, when called without a parameter, srand generates a new seed based on current circumstances (e.g. the time on the clock). Thus you should get a difference sequence and hence a different random number:
srand
rand(200)
Now, you may ask - why are you always getting the same sequence? I have no idea! As someone else suggested in one of the comments, the behavior you are seeing is the behavior one would expect if you had other code, anywhere, that calls srand with the same, fixed value every time. So it might be good to look for that.
Try Random.rand(). For example
Random.rand(200)
Or if you're working with an array you could use sample.
[*1..200].sample
rand(200) is run once and that value is assigned to your index variable. So 'index' will always be that number.
If you want index to change, you will need to continually run rand on it.
Here's a simple way to do that:
def randomIndex(num)
index = rand(num)
return index
end
randomIndex(200)
=> // this value will change

ruby shorthand for conditionals, when to use instance variables and efficiency of looping through parsed xml versus storing as hash

I'm learning ruby and have a few questions about some code I wrote for a newbie challenge. Purpose of challenge is to find country with largest population from an xml document.
I've included my code below. Questions I have are:
Is there a way to avoid having to initialize the #max_pop variable (#max_pop=0)?
Is there shorthand for combining the entire conditional block into 1 line?
Do I have to use instance vars #max_pop, #max_pop_country? Got error without them.
Which is more efficient:
Loop through each country and check if pop > max_pop (approach in code below)
Create pop hash (pop[:country]) and then find country with highest pop
Is there hash method to return key value pair for largest element in hash (to do 4.1)?
Source Code:
#max_pop=0
doc.elements.each("cia/country") do |country|
if country.attributes["population"].to_i > #max_pop
#max_pop=country.attributes["population"].to_i
#max_pop_country=country.attributes["name"]
end
end
puts "country with largest pop is #{#max_pop_country} with pop of #{#max_pop}
I am not familiar with rexml, but you ought to be able to simplify everything to something like this:
max_pop_elem = doc.elements.enum_for(:each, "cia/country").max_by { |c| c.attributes["population"].to_i }
max_pop_country = max_pop_elem.attributes["name"]
max_pop = max_pop_elem.attributes["population"].to_i
Yes, see above.
Yes, see above.
No. You should use local variables instead of instance variables when possible.
Don't worry about efficiency of CPU time until you have a slow program. Then use ruby-prof. Until then, just worry about the efficiency of coding time (do things the easy way).
Yes, just do key, value = hash.max_by{|k,v| v}.
In general, if you are going to be iterating over things you should learn about Ruby's Enumerable module. I made a reference sheet for it here.

Why won't this Ruby each loop break?

I have the following code in one of my personal projects:
def allocate(var, value) # Allocate the variable to the next available spot.
#storage.each do |mem_loc|
if mem_loc.free?
mem_loc.set(var, value) # Set it then break out of the loop.
break
end
end
end
Each item in the storage array is an object that responds to free? and set. What I am trying to do is cycle through the array, looking for the next free (empty) object to set the variable to. My problem is, this just cycles through every object and sets them all. Am I using the break function incorrectly?
Testing it, I call the following:
store.allocate(:a, 10)
store.allocate(:b, 20)
So store[1] should be set to :b and 20. But when I output the contents, it's value is 10, as is the rest of the array.
I believe I have found the mistake, and it wasn't actually in the code above.
When I set up the storage array, I did like so:
#storage = [Memory_location.new] * 1000
Believing it would create 1000 different objects. What I think actually happened, was that it created 1000 references to the same object, so when I changed one of them, I changed all of them. I could prove this by using the puts method on two different array locations, with both of them returning:
#{Memory_location:0x2bc8b74}

Resources