Home > Back-end >  How to write code for pyramid output in RUBY Language
How to write code for pyramid output in RUBY Language

Time:09-27

I'm a new web developer and need assistance generating a given output to a problem:

def fib(n)
    if (n<=2)
        return 1
    else
        return (fib(n-1) fib(n-2))
    end
end

puts "Enter the number of terms:-"
n=gets.chomp.to_i

puts "The first #{n} terms of fibonnaci series are:-"
for c in 1..n
    puts fib(c)
end 

OUTPUT:

Enter the number of terms:-
5
The first 5 terms of fibonnaci series are:-
1
1
2
3
5 

Excepted output:

1
22
333
55555
88888888

How would I be able to make my code produce the target output?

CodePudding user response:

You just need to iterate through the range and calculate fibonacci for every member and you can multuply string with *

def fibonacci(n)
  return n if (0..1).include?(n)
  fibonacci(n - 1)   fibonacci(n - 2)
end

def print_pyramide(n)
  (2..(n   1)).each do |i|
    fib = fibonacci(i)
    puts fib.to_s * fib
  end
end
print_pyramide(2)
# will print
# 1
# 22
print_pyramide(5)
# will print
# 1
# 22
# 333
# 55555
# 88888888

CodePudding user response:

You could use Enumerator::produce, which made it's debut in Ruby v2.7.

Enumerator.produce([1, 1]) { |n1, n2| [n2, n1   n2] }
          .with_index(1)
          .take(5)
          .each { |(_,f),i| puts f.to_s * i }

prints

1
22
333
5555
88888

Note:

enum = Enumerator.produce([1, 1]) { |n1, n2| [n2, n1   n2] }
  #<Enumerator: #<Enumerator::Producer:0x00007fb18084de18>:each>
enum.next #=> [1, 1]
enum.next #=> [1, 2]
enum.next #=> [2, 3]
enum.next #=> [3, 5]
enum.next #=> [5, 8]
  •  Tags:  
  • ruby
  • Related