trying to use each method to find divisible numbers and print them - ruby

I'm new to ruby and new to stack. I am trying to use the .each method on an array of numbers to see which numbers are divisible by 4, and 400. It is based on an exercises from Chris Pine's "Learn to Program" Ruby tutorial. In it you are supposed to find the leap years, then print them, from a range of years that the user inputs. I accomplished this using an if/else statement...but it seems to me this should be able to be done using the each method, or maybe the map method? Less code.
For example:
puts "Enter two years (to - from) to find out which years are leap years!"
puts "Enter the first year.."
year1 = gets.chomp.to_i
puts "Now enter the second year"
year2 = gets.chomp.to_i
range = (year1..year2).to_a
puts "These are the leap years between those years:"
range.each do |year|
leaps = (year % 4 == 0 || year % 400 == 0)
end
puts leaps
this code may not be correct, but i have toyed with different ways of doing it (puts inside .each, defining variable outside, etc...) but nothing seems to work. Like I said, I accomplished it with an if/else...I just feel there may be a better way, and it's driving me nuts. Do i not understand the .each correctly? am i using the wrong method? can it be done at all using each/map/or collect???? Thanks in advance!

You need to puts inside the each block too. Also, you can just divide by 4 and check if the remainder is 0. No need of 400
range.each do |year|
puts year if year % 4 == 0;
end
The puts year will be executed only if the if condition is satisfied.

Related

Ruby Countdown loop Learn Lab

I am currently working on a lab to create a countdown timer using a while loop and the subtract/assign operator. So far I have the loop counting 10 and breaking to 0 and printing my string "Happy New Year". I am not sure why it isn't iterating from 10 down to 0. Link to lab and code below https://learn.co/tracks/online-software-engineering-structured/procedural-ruby/looping/countdown-to-midnight-lab
number = 10
while number > 0
puts "#{number} SECOND(S)!"
number -= 1
break if n <= 0
puts "HAPPY NEW YEAR!"
end
end
There is one end too much. Proper indentation could have told you that.
puts "HAPPY NEW YEAR!" should probably be the last line, out of the loop (and probably without the puts).
n should be number
The task is in the form of a method which returns a string . puts however returns nil.

unique rand number in a ruby loop

I am reading the book "Learn to program", and I have come across an exercise that I am having trouble with.
year = (rand(1900...1990))
while true do
puts "What would you like to say to grandma?"
ask = gets.chomp
if
ask == ask.downcase
puts "SPEAK UP SONNY"
elsif
ask == ask.upcase
puts "NO, NOT SINCE #{year}!"
end
break if ask == "BYE"
end
everything is functioning properly, but if the rand number "year" comes up more than once, it repeats the same number. Is there a way to have it become a unique random number each time it comes up during the same loop?
thank you in advance
Move year assignment into the loop to have it assigned before each chomp.
The value of year does not change within the loop because it is defined outside the loop. It would change if the definition were moved inside the loop, but you still may have years repeated. To fix both of these problems, change
year = rand(1900...1990)
to
years = (1900...1990).to_a.shuffle
(outside the loop) and change
puts "NO, NOT SINCE #{year}!"
to
puts "NO, NOT SINCE #{years.shift}!"
(or years.pop). If this is repeated more than 91 times an exception will be raised.

String can't be coerced into Fixnum Ruby

I'm trying to learn ruby, and was tasked with creating a simple program that grabs user input, and then uses an elsif statement to give a possible 3 different answers. Here's my code:
print "What is your birth year?"
year = gets.chomp
age = 2016 - year
if age >= 40
puts "You're old!"
elsif age.between?(25, 39)
puts "You aren't too old!"
else
puts "You're just a baby!"
end
However, I keep getting "String can't be coerced into Fixnum"
I don't recall in the lessons doing something like I'm doing for the "age" variable, so I could be doing it wrong, but I also couldn't find an answer in my lessons or online. Any help would be greatly appreciated!
Remember that gets returns a string value, and in Ruby strings and numeric values are completely different things. Some other languages will coerce them as necessary, like PHP, Perl or JavaScript, but Ruby does not.
To make this work:
year = gets.chomp.to_i
Although technically to_i alone is usually sufficient.

Ruby programming double a penny a day for period of time

I am new, three wekks into Ruby as my first Language. here is the code I already have:
=begin
this program is to calculate doubling a penny a day for thirty one days
=end
puts "how many days would you like to calculate"
days = gets.chomp.to_i
i = 1
loop do
puts "#{i}"
break i >=100
end
I have tried to use ** as this is they syntax for exponential use. I have considered an until loop also, but the thing I am having most difficulty with is how to double per day each integer for given time.
I have also tried "#{i**2}" , "#{i**i}" , I have tried to google this problem for the past 2 days, to no avail.
It can be done using a simple bit shifting operation. Binary value "1" shifted left n times is used to calculate 2^n.
puts "how many days would you like to calculate"
days = gets.chomp.to_i
puts 1 << (days - 1)
You don't need any loop here. What about a power? If you want to double 1 penny in 31 days, you need to calculate 2^30:
puts "how many days would you like to calculate"
days = gets.chomp.to_i
puts 2 ** (days - 1)
Try:
# Display the question to the user in the terminal
puts 'How many days would you like to calculate?'
# Get the number of days from stdin
days = gets.chomp.to_i
# starting at 1 and up to the number of days start doubling. Reduce returns the result back to itself, thus doubling the return of each number until you have reached the up to limit.
result = 1.upto(days).reduce { |start| start * 2 }
# Put the result
puts result
31.times.reduce 1 do |a| a * 2 end
#=> 2147483648

Ruby: rand method is not giving me a truly random number

I am trying to answer the following question from Chris Pine "Learn to Program" book:
• Write a Deaf Grandma program. Whatever you say to grandma (whatever
you type in), she should respond with HUH?! SPEAK UP, SONNY!, unless
you shout it (type in all capitals). If you shout, she can hear you
(or at least she thinks so) and yells back, NO, NOT SINCE 1938! To
make your program really believable, have grandma shout a different
year each time; maybe any year at random between 1930 and 1950. (This
part is optional, and would be much easier if you read the section on
Ruby's random number generator at the end of the methods chapter.)
You can't stop talking to grandma until you shout BYE. Hint: Don't
forget about chomp! 'BYE'with an Enter is not the same as 'BYE'
without one! Hint 2: Try to think about what parts of your program
should happen over and over again. All of those should be in your
while loop.
• Extend your Deaf Grandma program: What if grandma doesn't want you
to leave? When you shout BYE, she could pretend not to hear you.
Change your previous program so that you have to shout BYE three times
in a row. Make sure to test your program: if you shout BYE three
times, but not in a row, you should still be talking to grandma.
My code is giving me the same "random_year" when I run it. Why is the code not providing me an actual random year (between 1930 and 1950)?
Code in ruby.
# Deaf Grandma
random_year = 1930 + rand(1950 - 1930)
puts 'WHAT DO YOU WANT KID?'
bye = 0
talk_to_grandma = nil
while bye < 3
talk_to_grandma = gets.chomp
if talk_to_grandma == "BYE"
puts 'NO, NOT SINCE ' + random_year.to_s
bye+=1
elsif talk_to_grandma == talk_to_grandma.upcase
puts 'NO, NOT SINCE ' + random_year.to_s
bye = 0
else
puts "HUH?! SPEAK UP, SONNY!"
bye = 0
end
end
You need to generate the random number inside your loop. Right now you generated it ONCE at the start of the program, and then it never changes. Basically:
while bye < 3
random_year = 1930 + rand(1950 - 1930) // move the random generation to here
puts 'NO, NOT SINCE ' + random_year.to_s
You have assigned a value to the random_year variable in the first code line. It is selected randomly.
On each call to
puts 'NO, NOT SINCE ' + random_year.to_s
the variable is accessed/read, but not modified.
You may want to encapsulate the random year generation in a method:
def random_year( start=1930, range = 20 )
start + rand( range )
end
then you can use it like this:
puts "NO, NOT SINCE #{random_year}"
or, for a slightly older grandma:
puts "NO, NOT SINCE #{random_year(1910, 50)}"
For that exercise I've used: rand(1930..1950)

Resources