Ruby error: undefined method `shift' - ruby

Brand new to Ruby. There are a couple of array methods I can't access.
EDIT:
I originally had:
puts 'give me a number to find phi of: '
K = gets
List = Array.new(K) #{|i| i}
List.drop(2)
List puts
Rec'd the error: in `initialize': no implicit conversion of String into Integer
so I changed line 3 above to:
List = Array.new(K.to_i) #{|i| i}
and am now receiving: undefined method `List' for main:Object
I'm trying to create an array based on user input, then drop or shift the first 2 elements of the array (the 0 and 1)
=================================
original post was unclear:
puts 'give me a number to find phi of: '
K = gets
puts K.shift
I'm sure it's something easy but can't figure it out. Am I missing a basic library or something? Any help would be appreciated!

This is the shortest way to find all primes between 2 and K in Ruby, you don't have to invent your own algo for finding primes when there's one already(http://ruby-doc.org/stdlib-1.9.3/libdoc/prime/rdoc/Prime.html)
require 'prime'
def find_primes_between_2_and(a_number)
Prime.each(a_number).map do |prime|
prime
end
end
puts 'Give me a number up to which to find primes:'
number = gets.to_i
puts find_primes_between_2_and(number)

I'm running thru Chris Pike's Ruby "Learning to Program" & am doing it as an exercise. But hey, thanks for the help.
My problem on the shift was passing it w/o a parameter. It should have been List.shift(2)
Thanks much!

Related

ruby how could i make this factorization recursive till i end with a binary number?

i have this code, basically first i factorize for example the number 28 to:
[2,2,7]
and then i make a list of prime numbers and find the index of each factor in that list, so 2 is prime number with index 0 and 7 prime number with index 2 so it ends up like this:
[[0],[0],[2]]
with which another recursion would be:
[[0],[0],[[0]]]
which tranlated to binary would be:
1101101110111
but im stuck on this:
require 'prime'
def f(n)
Prime.prime_division(n).flat_map { |factor, power| [factor] * power }
end
n=rand(10000)
puts n
f=f (n)
require 'prime'
#list=Prime.take(10000)
g=[]
j=0
f.each do |j|
if j>10
i=f(#list.index(j))
g.push i
i=[]
else
g.push j
end
end
print g
You want to learn, so I won't do all the work for you.
Step 1
Please write those 3 methods :
def get_factors(integer)
# return an Array of Integers:
# get_factors(28) -> [2,2,7]
end
def get_factor_index(prime)
# return the index of prime in Prime.all :
# 2 -> 0
# 7 -> 2
end
def array_to_binary(nested_array)
# convert nested_array (with 0s in leaves) to binary
# [[0],[0],[[0]]] -> "1101101110111"
# Hint : Use Array#to_s, and then String#gsub 3 times to convert ',' to '', and '[' or ']' to 1
end
and come back once you're done. We'll work on the recursion.
Step 2
I modified a bit your answer just a bit. To make it clearer, I tried to use different names for variables and methods. Also, the last line of a method is returned automatically by Ruby. You don't need to define an extra variable. Methods could probably be written more efficiently but I didn't want you to not recognize your code.
Your get_factor_index does more than what I asked for BTW. I'm not sure we can use it like this :
require "prime"
def get_factors(integer)
Prime.prime_division(integer)
end
def nested_array(factors)
factors.flat_map { |factor, power| [factor] * power }
end
def get_factor_index(nested_array)
list=Prime.take(10000)
temp=[]
nested_array.each do |i|
p = list.index(i)
temp.push(p)
end
temp
end
def array_to_binary(array)
temp=array.to_s
temp=temp.gsub("[","1")
temp=temp.gsub("]","1")
temp=temp.gsub(",","")
temp.gsub(" ","")
end
Now, please write a method that uses all the above ones, converting 512 to "10000000001". I'm not sure it's the correct answer, but we'll work on that later.
Also, try this method on 20 (not 28!) and see what you get. Using the above methods, you could try to manually tailor a way to get [[0],[0],[2]]. It's not a problem if it just works for 20 at first.
If you're feeling adventurous, try to get [[0],[0],[[0]]] with the above methods.

Fibonacci number on a range (ruby)

Could someone give me a brief explanation as to why n+(n-1) doesn't work? Mathematically it does but i'm not sure how to tell ruby this is what i'm looking for? As the title suggests, the code is supposed to return a Fibonacci sequence.
startyear = []
(1..100).each do |n|
puts n+(n-1)
startyear.push(n)
end
n+(n-1) = 2n-1. Your code is simply displaying 2n-1 (1,3,5,7,..,199).
On the other hand, startyear.push(n) is pushing numbers (1,2,3,.,100) into the startyear array. I think you meant to do something like this.
startyear = [1,1]
(2..100).each do |n|
puts (new_num = startyear[n-1] + startyear[n-2])
startyear.push(new_num)
end
But again, I'm not 100% sure what the range stands for in your code, so I might be wrong.

Building a ruby factorial calculator

I'm working on writing a factorial program in ruby and I'm trying to write it where it does as follows:
Asks the user to enter a value to perform factorial on
takes in that value entered
performs factorial on it
and 4. returns the factorial value using "puts"
My goal is to get this to work then expand on this by building it out to include other statistical functions.
So far this is the code I have:
puts "Welcome to the Calculator for Ruby"
puts "Please enter your value to value"
#N factorial value
def n
n = gets.chomp
end
def fact
n * fact(n-1)
end
puts fact(n)
Fyi, I might add I've seen the generic factorial code available on the web but what I'm trying to do is set it so that the user defines n rather than setting n statically but when I try to do it, my code as above is erroring with the below error message:
"fact" : wrong number of arguments (1 for 0) (ArgumentError)
My apologies for some of the wording and not including a specific question. My question would be 3 parts:
How would I properly write the factorial calculation to operate on the user provided value? (Which I see was answered).
Once the calculation is performed how can I store that value so it persists in case the user wants to recall it for other calculations.
Lastly, are there any good sources for guidance in writing statistical functions in ruby?
Thank you to all for the assistance
No need to declare n using def, simply assign it (e.g. as n = gets.chomp).
You must include a named argument to your fact function, like def fact(x).
The fact(x) function needs a base case since you are using recursion.
You must convert the user input string n to a number, like n.to_i.
puts "Welcome to the Calculator for Ruby"
puts "Please enter your value to value"
def fact(x)
(x <= 1) ? 1 : x * fact(x-1)
end
n = gets.chomp.to_i
puts "#{n}! => #{fact(n)}"
Simpler way. Just inject numbers from 1 till n.
puts 'Welcome to the Calculator for Ruby'
puts 'Please enter your value to value'
n = gets.chomp.to_i
puts (1..n).inject(:*)
Might no be the best of solutions but here you go
puts "Welcome to the Factorial Calculator for Ruby"
puts "Please enter your value to exaluate"
n = gets.chomp.to_i
def fact(num)
return num <= 1 ? 1 : num * fact(num - 1)
end
puts "The factorial of #{n} is #{fact(n)}

Type Error - No implicit conversion from nil to integer - Creating a array

I'm new to Ruby. I'm trying to learn the dos and don'ts by making little programs. This program is a little redundant, but I wanna better myself with the syntax of the language.
Anyways, so I'm trying to create a little program that will ask the user for an amount of people. This amount of people will then reference the size of the array, then the program will ask the user to enter the names for each element in the array (which ALL be "nil" values since the new array's elements will be empty). Finally, I would want to print back the array to the console to see the completed elements.
However, I'm getting an error saying "Line 10: TypeError occured. No implicit conversion from nil to integer". My code is not 100% done. I'm still trying to add more stuff to it, but I want to troubleshoot this error first before I go about doing that. Anyone out there willing to help me out ?
Here's the code
def Array_Maker
puts "How many people would you like to enter? : "
num = gets.chomp.to_i
nameArray = Array.new(num)
puts "\nEnter the names of the people you wish to add: "
nameArray.each do |x|
nameArray[x] = gets.chomp.to_s
end
nameArray.each do |x|
puts x
end
end
Array_Maker()
I'm probably doing this all wrong, but I'm trying...
The line nameArray.each do |x| iterates over the array and x is set to the value of the array at each index.
A better way might be to build the array using a map method. Something like this:
def array_maker
puts "How many people would you like to enter? : "
num = gets.chomp.to_i
puts "\nEnter the names of the people you wish to add: "
nameArray = num.times.map do
gets.chomp.to_s
end
nameArray.each do |x|
puts x
end
end
array_maker()
nameArray.each do |x| In this loop, x is given the values of the Array which is nil
Try this.
for i in 0..num do
nameArray[i] = gets.chomp.to_s
end

help with a simple method

Hi I'm trying to solve the exercise from https://github.com/alexch/learn_ruby
I must write a method which should "multiplies two numbers" and "multiplies an array of numbers". I'm fresh to ruby and solved it, with only one method like this:
def multi(*l)
sum = 1
l.flatten! if l.is_a? Array
l.each{|i| sum = sum*i}
return sum
end
I'm sure there are better ways, so how can I improve this method? to a more ruby like syntax :)
The if l.is_a? Array is not necessary because the way multi is define, l will always be an array.
The pattern
result = starting_value
xs.each {|x| result = result op x}
result
can be written more succinctly using xs.inject(starting_value, :op).
So you can write your code as:
def multi(*l)
l.flatten.inject(1, :*)
end
If you're ok, with calling the method as multi(*array) instead of multi(array) to multiply an array, you can leave out the flatten, as well.

Resources