Taking data from a loop and putting it into an array - ruby

I am trying to make a small program that find the multiples of a number.
def process
i = 1
while i < 1000
#value1 * i
i + 1
end
end
What I need to do is take EACH the result from the multiplication and put that into an array called #multiple1
Please help as this is (kind of) the first ruby program that I have written on my own.

The simple way to do this is the following:
def process
i = 1
#multiple1 = []
while i < 1000
#multiple1 << #value1 * i
i += 1
end
end
The equivalent, but more Ruby-like way looks like this:
#multiple1 = (1..999).map { |i| #value1 * i }

Related

how to do reverse operation in ruby using one variable with out using any built in functions

str="karhik reddy"
n= str.length
for i in n.downto(0) do // reverse iteration of ruby
str += str[i].to_s
end
puts str[-n..-1]
Is this efficient for larger data sets? Like an array of millions of numbers where you would reverse the complete character set in a book?
Down to 3 methods:
"karhik reddy".each_char.inject(&:prepend)
If you want to do this caveman style with no "built-in functions", the closest you can do is:
def primitive_reverse(str)
out = ''
i = 0
while (i < str.length)
i += 1
out << str[-i]
end
out
end
Where technically String#<<, String#[] and String#length are all methods, but without that you're unable to complete this.
I would say, the most efficient way should be smth like:
> str = "karhik reddy"
> (n = str.length).times { |i| str[i...i], str[n..n] = str[n-1], '' }
> str
#⇒ "ydder kihrak"

How can I collect block values in Ruby without an iterator?

Here's some code:
i = 0
collection = []
loop do
i += 1
break if complicated_predicate_of(i)
collection << i
end
collection
I don't know in advance how many times I'll need to iterate; that depends on complicated_predicate_of(i). I could do something like 0.upto(Float::INFINITY).times.collect do ... end but that's pretty ugly.
I'd like to do this:
i = 0
collection = loop.collect do
i += 1
break if complicated_predicate_of(i)
i
end
But, though it's not a syntax error for some reason, loop.collect doesn't seem to collect anything. (Neither does loop.reduce). collection is nil at the end of the statement.
In other words, I want to collect the values of a loop statement without an explicit iterator. Is there some way to achieve this?
You could write
collection = 1.step.take_while do |i|
i <= 3 # this block needs to return *false* to stop the taking
end
Whatever solution you choose in the end, remember that you can always opt to introduce a helper method with a self-explanatory name. Especially if you need to collect numbers like this in many places in your source code.
Say you wanted to hide the intricate bowels of your solution above, then this could be your helper method:
def numbers_until(&block)
i = 0
collection = []
loop do
i += 1
break if yield i
collection << i
end
collection
end
collection = numbers_until do |i|
i > 3 # this block needs to return *true* to stop the taking
end
You could write
def complicated_predicate_of(i)
i > 3
end
1.step.with_object([]) { |i,collection| complicated_predicate_of(i) ?
(break collection) : collection << i }
#=> [1, 2, 3]

Global vs local variables?

I am wondering why my code works in one instance but doesn't in another. Does it have something to do with local and global variables?
This works:
def factorial num
result = 1
while (num > 1)
result = result * num
num -= 1
end
puts result
end
This doesn't work:
result = 1
def factorial num
while (num > 1)
result = result.to_i * num
num -= 1
end
puts result
end
Everything inside of a method definition cannot see local variables from other places. That sounds weird, but here's two ways to fix it:
result = 1
number = 10
def factorial(num,result_value)
while (num > 1)
result_value = result_value.to_i * num
num -= 1
end
puts result_value
end
factorial(number, result)
That passes result as an argument. That's a great way of handling the method because it doesn't allow you to change the value of result from within the method. That might not seem like a big deal but "pure methods" like this become very valuable as the size the code increases.
This is the "dirty" or un-pure way of doing the same thing:
#result = 1
def factorial(num)
while (num > 1)
#result = #result.to_i * num
num -= 1
end
puts #result
end
Putting an # in front of a variable name allows its scope to expand to methods defined outside of its scope. This becomes a problem as the complexity of your code increases.
Random personal opinion: even though Ruby doesn't require you to put the parentheses next to a method definition, you always should. It makes the code a lot more explicit and easier to read. Follow your heart though ;)
You could experiment by prepending all results with a $ sign, making it global. Prepending with a # results in an instance variable, also interesting. Sidenote: puts prints and returns nil, so your method returns nil.
result = 1 # line 1
def factorial num
while (num > 1)
result = result.to_i * num
num -= 1
end
puts result
end
In this code, factorial doesn't know about result variable from the line 1.
When Ruby find result = result.to_i * num in your method it will first assign nil to the result. Then Ruby will try to run result.to_i * num. Since result is already nil, result.to_i is equal 0.
Here is another example:
def foo
a = a
puts "#{a.class}"
end
foo #NilClass
In the Doesn't Work version the result variable you've assigned to 1 isn't visible inside the factorial method.
Now there is a possibly unexpected behaviour in Ruby that if you try to assign a variable and you refer to the same variable on the right hand side of the assignment, if that variable doesn't have a value yet then it is treated as nil rather than raising an error. So the first time round the loop when you perform
result = result.to_i * num
it's equivalent to result = nil.to_i * num and nil.to_i is equal to 0 so this then sets up result to be 0 for subsequent iterations of the loop and as you're just multiplying the value of result stays on 0.

Monte Carlo Simulation in Ruby

Hey I have a problem with my simulation.
I am a Ruby-Starter and don't know what's wrong in my code. That is only the part with the simulation:
def mean
mean = self.reduce(:+)/self.length.to_f
return mean
end
def randn
begin
rg1 = (rand*2)-1
rg2 = (rand*2)-1
q = rg1**2 + rg2**2
end while (q == 0 || q > 1)
p = Math.sqrt((-2*Math.log(q))/q)
rn1 = rg1 * p
rn2 = rg2 * p
return rn1, rn2
end
monte_carlo = 10
ren1_sim = Array.new
ren2_sim = Array.new
monte_carlo.times {
(1..20).each{ |i|
(1..250).each { |j|
r = randn()
ren1= * Math.exp(mu_ren1 + sigma_ren1 * r[0])
# ren1 is an array with prices, mu_ren1 and sigma_ren1 are individual values
ren2= * Math.exp(mu_ren2 + chol_21 * r[0] + chol_22 * r[1])
# chol_21 and chol_22 are also individual values
ren1_sim.push(ren1)
ren2_sim.push(ren2)
}
}
}
puts ren1_sim.mean
puts ren2_sim.mean
I don't get an error without the last two puts, but when I want to calculate the average of the arrays ren1_sim and rent_sim I get the error:
undefined method 'mean' for #<Array:0x2acf318> (NoMethodError)
Do you know how to fix that?
You're trying to invoke mean on an Array, which is not a method of Array. Perhaps you meant to use Statsample::Vector, which is Statsample's extension of Array, and does have mean?
ren1_sim = Statsample::Vector.new
ren2_sim = Statsample::Vector.new
You can also call to_vector on an Array instance to get a Statsample::Vector.
You've defined a mean method at the top of your file, but that just creates a method on the top level object, and you're trying to call it on an individual array. You could either change that code to
def mean(array)
array.reduce(:+)/array.length.to_f
end
and then change your usage of it later on to mean(ren1_sim)
or change your code so that you are adding the method to array, i.e.
class Array
def mean
self.reduce(:+)/self.length.to_f
end
end
have a look at this post to calculate the average of a array
How do I create an average from a Ruby array?

In Ruby, how can I collect each new element passing through a method into an array?

I'm creating a small prime number program, and am confused about one thing.
I have a function called create_numbers, that generates numbers and passes them to a new function called check_for_primes, which passes only prime numbers to a final function called count_primes. I want to collect each prime into an array in the function count_primes, but for some reason each number is collected as its own array.
Any idea of what I'm doing wrong?
Here is the code:
def create_numbers
nums = 1
while nums < 100
nums = nums + 2
check_for_primes(nums)
end
end
def count_primes(nums)
array = []
array << nums
puts array.inspect
end
def check_for_primes(nums)
(2...nums).each do |i|
if nums%i == 0
nums = false
break
end
end
if nums != false
count_primes(nums)
end
end
create_numbers
Try this:
START = 1
STEP = 2
class Integer
def prime?
return if self < 2
(2...self).each do |i|
return if self % i == 0
end
true
end
end
def create_numbers
num = START
while (num + STEP) < 100
num += STEP
primes << num if num.prime?
end
end
def primes
#primes ||= []
end
create_numbers
p primes
When you want to save the 'state' of something, put it in an instance variable (#var).
It'll be accessible outside of the current function's scope.
Also, try naming your variables differently. For instance, instead of 'nums', in the
create_numbers method, use 'num'. Since the variable is only referencing one number at a
time and not a list of numbers, naming it in the plural will confuse people (me included)...
Hope it helps,
-Luke
each time into count_primes you put a value into array (which should have a better name, btw). Unfortunately, each time it's a new variable called array and since no one outside the function can see that variable it's lost when the function ends. If you want to save the values you've already found you'll need to set some state outside your function.
I can think of 2 quick solutions. One would be to declare your storage at the top of create_numbers and pass it into both functions.
def count_primes(num, arr)
def check_for_primes(nums, arr)
The other would be to set a variable outside all the functions, $array, for example to hold the values.
$array = []
...
$array << num
Since the scope of $array is global (i.e. all functions have access to it) you have access to it from anywhere in the file and can just add things to it in count primes. Note that using globals in this way is generally considered bad style and a more elegant solution would pass parameters and use return values.

Resources