Solving foobar in Ruby? - ruby

So far I have been able to get the numbers to print properly but I don't know how to loop them.
puts "Please enter a number"
val1 = gets.to_i
val2 = val1 % 3
val3 = val1 % 5
def ordinal(a,b,c)
if b == 0 && c == 0
return "foobar"
elsif b == 0
return "foo"
elsif c == 0
return "bar"
else
return a
end
end
val5 = ordinal(val1,val2,val3)
puts "#{val5}"
I also made a loop that works but it won't recognize strings.
n = 0
x = gets.to_i
while n != x
puts "#{n}"
n = n + 1
end
How do I combine my method and loop? Or is there any other way to solve this? But I would prefer if you solve it using my code IF its any good off course so that I can understand it better.

As par your comments, the loop part is easy when leveraging Integer#times.
This is what you have that works for you:
puts "Please enter a number"
val1 = gets.to_i
val2 = val1 % 3
val3 = val1 % 5
def ordinal(a,b,c)
if b == 0 && c == 0
return "footer"
elsif b == 0
return "foo"
elsif c == 0
return "bar"
else
return a
end
end
val5 = ordinal(val1,val2,val3)
puts "#{val5}"
Right now you're just running through the final number. Try using the Integer#times to run a loop up to the number...:
puts "Please enter a number"
num = gets.to_i
num.times do |a|
a += 1 # counting is done from 0 to n-1
b = a % 3
c = a % 5
if b == 0 && c == 0
print "foobar "
elsif b == 0
print "foo "
elsif c == 0
print "bar "
else
print "#{a} "
end
end
print "\n"
Personally I would probably have written this a bit differently, but I guess it's sound enough.
I would probably write something messy because I hate long if...else statements...:
def foo_bar n
n.times {|i| i+=1; print( (i%15==0 && "FooBar ") || (i%3==0 && "Foo ") || (i%5 ==0 && "Bar ") || ("#{i} ") ) }
print "\n"
end
puts "Enter number:"
foo_bar gets.to_i

You can do this too:
def foobar n
n.times do |i|
i += 1
num = ""
num << "Foo" if i % 3 == 0
num << "Bar" if i % 5 == 0
num = i.to_s if num == ""
puts num
end
end
foobar 15
The logic is simpler than Myst's.
You don't need to test if it's a factor of 15.
Output:
1
2
Foo
4
Bar
Foo
7
8
Foo
Bar
11
Foo
13
14
FooBar
=> 15

Related

FizzBuzz Program Output in form of table

I have written the logic for the program to perform FizzBuzz operations:
fizzbuzz
module FizzBuzz
class Operation
def input
puts 'Enter a number upto which Fizz/Buzz needs to be printed'
num = gets.chomp.to_i
fizzbuzz_function(num)
end
def fizzbuzz_function(num)
for i in 1..num
if i % 3 == 0 && i % 5 == 0
puts 'FizzBuzz'
elsif i % 3 == 0
puts 'Fizz'
elsif i % 5 == 0
puts 'Buzz'
else
puts i
end
end
end
end
res = Operation.new
res.input
end
But I am trying to print the output in form of a table.
Here is FizzBuzz in form of a table:
def fizzbuzz_gen(num)
Enumerator.new do |y|
(1..num).each do |i|
if i % 3 == 0 && i % 5 == 0
y << 'FizzBuzz'
elsif i % 3 == 0
y << 'Fizz'
elsif i % 5 == 0
y << 'Buzz'
else
y << i.to_s
end
end
end
end
def fill_to_width(width, e)
result = ""
future_length = -1
while result.length + future_length < width
result << e.next
result << " "
future_length = e.peek.length
end
result.center(width)
end
def format_table(num)
fb = fizzbuzz_gen(num)
begin
puts fill_to_width(75, fb)
puts fill_to_width(75, fb)
loop do
puts "%10s%s%31s%s" % ["", fill_to_width(12, fb), "", fill_to_width(12, fb)]
end
rescue StopIteration
end
end
format_table(100)
There may be less numbers output than specified, in order for one leg not to be shorter than another.

Total newb here and other fizzbuzz issue

I'm trying to write a looping fizzbuzz code that ends with the user_input's number. So far the code works, but it loops the number of times you put in for the user_input, not end at the user_input's limit. For example, if I type in 25, it will loop 25 times, and not end at 25. How do I set the parameters/range?
Here is my code:
puts("Please select a number that is at least 25. This is the limit for the fizzbuzz game.")
user_input = gets().chomp().to_i
if
user_input < 25
puts("Please select a larger number.")
else
user_input >= 25
user_input = user_input
counter = 1
while counter < user_input
puts(counter)
counter = counter + 1
(1..user_input).step do |i|
if i % 3 == 0 && i % 5 == 0
puts("fizzbuzz")
elsif i % 3 == 0
puts("fizz")
elsif i % 5 == 0
puts("buzz")
else
puts(i)
end
end
end
end
It is optional to write () when you send no parameters to a method and usually discouraged
You shouldn't use else user_input >= 25, else is enough
user_input = user_input is totally useless line
while cycles with counters isn't the way rubists code, prefer iterators. Moreover, you shouldn't have while here at all
puts 'Please select a number that is at least 25. This is the limit for the fizzbuzz game.'
user_input = gets.chomp.to_i
if user_input < 25
puts 'Please select a larger number.'
else
1.upto(user_input) do |i|
if i % 3 == 0 && i % 5 == 0
puts 'fizzbuzz'
elsif i % 3 == 0
puts 'fizz'
elsif i % 5 == 0
puts 'buzz'
else
puts i
end
end
end
optionally, you can use case-when instead of multiple elsif statements:
puts 'Please select a number that is at least 25. This is the limit for the fizzbuzz game.'
user_input = gets.chomp.to_i
if user_input < 25
puts 'Please select a larger number.'
else
1.upto(user_input) do |i|
case
when [3, 5].all? { |n| i % n == 0 }; puts 'fizzbuzz'
when i % 3 == 0; puts 'fizz'
when i % 5 == 0; puts 'buzz'
else; puts i
end
end
end

ruby code stopping at run time, seemingly an infinite loop

if i run the code, it will stop and not do anything and i am unable to type. seems to be an infinite loop.
the problem seems to be the end until loop, however if i take that out, my condition will not be met.
can anyone find a solution? i have tried all the loops that i can think of.
/. 2d array board ./
board = Array.new(10) { Array.new(10, 0) }
/. printing board ./
if board.count(5) != 5 && board.count(4) != 4 && board.count(3) != 3
for i in 0..9
for j in 0..9
board[i][j] = 0
end
end
aircraftcoord1 = (rand*10).floor
aircraftcoord2 = (rand 6).floor
aircraftalign = rand
if aircraftalign < 0.5
for i in 0..4
board[aircraftcoord2+i][aircraftcoord1] = 5
end
else
for i in 0..4
board[aircraftcoord1][aircraftcoord2+i] = 5
end
end
cruisercoord1 = (rand*10).floor
cruisercoord2 = (rand 7).floor
cruiseralign = rand
if cruiseralign < 0.5
for i in 0..3
board[cruisercoord2+i][cruisercoord1] = 4
end
else
for i in 0..3
board[cruisercoord1][cruisercoord2+i] = 4
end
end
destroyercoord1 = (rand*10).floor
destroyercoord2 = (rand 8).floor
destroyeralign = rand
if destroyeralign < 0.5
for i in 0..2
board[destroyercoord2+i][destroyercoord1] = 3
end
else
for i in 0..2
board[destroyercoord1][destroyercoord2+i] = 3
end
end
end until board.count(5) == 5 && board.count(4) == 4 && board.count(3) == 3
print " "
for i in 0..9
print i
end
puts
for i in 0..9
print i
for j in 0..9
print board[i][j]
end
puts
end
The line board.count(5) == 5 ... will never be true because board is a two-dimensional array. I can't tell what the condition should be, but it could look something like:
board[5].count(5) == 5

Fizz Buzz in Ruby for dummies

Spoiler alert: I am a true novice. Tasked with figuring out fizz buzz in
ruby for a class and while I have found more than a few versions of code
that solve the problem, my understanding is so rudimentary that I cannot
figure out how these examples truly work.
First question(refer to spoiler alert if you laugh out loud at this):
How do i print out numbers one through 100 in Ruby?
Second question: can 'if else" be used to solve this? My failed code is
below(attachment has screen shot):
puts('Lets play fizzbuzz')
print('enter a number: ')
number = gets()
puts(number)
if number == % 3
puts ('fizz')
elsif number == % 5
puts ('buzz')
elsif number == %15
puts ('fizzbuzz')
end
Thanks,
Thats ok being a novice, we all have to start somewhere right? Ruby is lovely as it get us to use blocks all the time, so to count to 100 you can use several methods on fixnum, look at the docs for more. Here is one example which might help you;
1.upto 100 do |number|
puts number
end
For your second question maybe take a quick look at the small implementation i whipped up for you, it hopefully might help you understand this problem:
1.upto 100 do |i|
string = ""
string += "Fizz" if i % 3 == 0
string += "Buzz" if i % 5 == 0
puts "#{i} = #{string}"
end
First question: this problem has several solutions. For example,
10.times { |i| puts i+1 }
For true novice: https://github.com/bbatsov/ruby-style-guide
another method that can be helpful :
puts (1..100).map {|i|
f = i % 3 == 0 ? 'Fizz' : nil
b = i % 5 == 0 ? 'Buzz' : nil
f || b ? "#{ f }#{ b }" : i
}
As a one liner
(1..100).map { |i| (i % 15).zero? ? 'FizzBuzz' : (i % 3).zero? ? 'Fizz' : (i % 5).zero? ? 'Buzz' : i }
In Regards to your failed code, your conditional statements should be like this:
if number % 3 == 0
puts "Fizz"
end
if number % 5 == 0
puts "Buzz"
end
You don't want the last elsif statement because it will never get executed
(if a number is not divisible by 3 or divisible by 5, then it is certainly not divisible by 15)
Adjust for this by changing the second elsif to simply and if and if the number is divisble by 5 and not by 3, then Fizz will not be outputted but Buzz Will be
I'm just showing you how to correct your code, but as others have pointed out, there are far more elegant solutions in Ruby.
Not the most beautiful way to write it but good for beginners and for readability.
def fizzbuzz(n)
(1..n).each do |i|
if i % 3 == 0 && i % 5 == 0
puts 'fizzbuzz'
elsif i % 3 == 0
puts 'fizz'
elsif i % 5 == 0
puts 'buzz'
else
puts i
end
end
end
fizzbuzz(100)
1.upto(100).each do |x| # Question #1 The 'upto' method here takes is
# what you would use to count in a range.
if (x % 3 == 0) && (x % 5 == 0)
puts " Fizzbuzz"
elsif x % 3 == 0
puts " Fizz"
elsif x % 5 == 0
puts " Buzz"
else
puts x
end
end
Question #2 Yes you can but I would look for a more elegant way to write this as a part of a definition like
def fizzbuzz(last_number)
1.upto(last_number).each do |x|
if (x % 3 == 0) && (x % 5 == 0)
puts " Fizzbuzz"
elsif x % 3 == 0
puts " Fizz"
elsif x % 5 == 0
puts " Buzz"
else
puts x
end
end
end
This is the answer that helped me to understand that no variables are being created with the .each method. Sorry about my indenting. Still learning how to use Stackoverflow text editing.
As for a more complex solution, that's one way you could build
a simple DSL for quickly modifying the FizzBuzz programme (adding new divisors with their own keywords)
class FizzBuzzer
# #return [Hash{String, Symbol => Integer}]
attr_reader :keywords
# #param keywords [Hash{String, Symbol => Integer}]
def initialize(keywords)
#keywords = keywords
end
# #param range [Range]
# #return [void]
def call(range)
range.each do |num|
msg = ''
#keywords.each do |name, divisor|
msg << name.to_s if (num % divisor).zero?
end
msg = num if msg.empty?
puts msg
end
puts
end
end
# create a fizz buzzer with custom keywords for divisors
CLASSIC_FIZZ_BUZZER = FizzBuzzer.new Fizz: 3, Buzz: 5
# print for a particular range
CLASSIC_FIZZ_BUZZER.call(1..25)
# you can easily define an extended fizz buzzer
EXTENDED_FIZZ_BUZZER = FizzBuzzer.new Fizz: 3, Buzz: 5, Bazz: 7, Fuzz: 11 # print 'Fuzz' when divisible by 11
EXTENDED_FIZZ_BUZZER.call(1..25)
Here's a quite elegant solution.
(1..100).each do |num|
msg = ''
msg << 'Fizz' if (num % 3).zero?
msg << 'Buzz' if (num % 5).zero?
msg = num if msg.empty?
puts(msg)
end
It can be even more compact
(1..100).each do |num|
(msg ||= '') << 'Fizz' if (num % 3).zero?
(msg ||= '') << 'Buzz' if (num % 5).zero?
puts msg || num
end
FizzBuzz
(1..100).each do |num|
if num % 3 == 0 && num % 5 == 0
puts "#{num}. FIZZBUZZ!"
elsif num % 3 == 0
puts "#{num}. FIZZ!"
elsif num % 5 == 0
puts "#{num}. BUZZ!"
else
puts "#{num}."
end
end
First question:
for i in 1..100
puts i
end
Here is my most "idiomatic ruby" solution:
class FizzBuzz
def perform
iterate_to(100) do |num,out|
out += "Fizz" if num.divisable_by?(3)
out += "Buzz" if num.divisable_by?(5)
out || num
end
end
def iterate_to(max)
(1..max).each do |num|
puts yield num,nil
end
end
end
class Fixnum
def divisable_by?(num)
self % num == 0
end
end
class NilClass
def +(other)
other
end
end
FizzBuzz.new.perform
And it works:
https://gist.github.com/galori/47db94ecb822de2ac17c

If type is character I want to puts error

puts "Let's sum many numbers"
sum = 0
num = 0
while(num != 'x')
puts "Press a number and then Enter if you exit press 'x'"
num = gets.chomp
if num != 'x'
num = num.to_i
print "#{sum} + #{num} = "
sum += num
puts "#{sum}"
elsif num == 'x'
puts "Total sum is #{sum}"
break
else
puts "error!"
end
end
I want to make code to show error If user press char except 'x'.
How should I do?
Change your first if to a condition that checks if the input is a number, e.g.
if num =~ /\A[0..9]+\z/ # or /\A\d+\z/
The way your code is currently, all strings except 'x' are treated as number -- with value 0 in case they aren't really numbers:
'foobar'.to_i # => 0

Resources