TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to RUBY

Ruby Fibonacci Sequence Example

Compute Fibonacci numbers. Use the times iterator to iterate and return values.
Fibonacci. This sequence is composed of numbers. Each number is equal to the previous two numbers added together. Fibonacci sequences occur in nature and have many uses.
With iteration, we can quickly compute a Fibonacci number. In Ruby we use iterators, like "times," for the most elegant code. This makes programs simpler to understand.
Example def. Let us begin. We introduce a fibonacci() method. This receives an integer and returns another one. It receives the position of the Fibonacci sequence we want to compute.

Times: To compute a Fibonacci number, we use times to iterate over each position to the current position. We add up the numbers.

Temp: We need to use a temporary value (temp) because we reassign the variable "a" but do not want to lose its value.

Ruby program that computes Fibonacci numbers def fibonacci(n) a = 0 b = 1 # Compute Fibonacci number in the desired position. n.times do temp = a a = b # Add up previous two numbers in sequence. b = temp + b end return a end # Write first 15 Fibonacci numbers in sequence. 15.times do |n| result = fibonacci(n) puts result end Output 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Results. One of my major goals is not to post incorrect code. I tested the results of this def against other Fibonacci methods, and it yields the correct results.
Memoization. This method is slow for repeated computations. We can instead memoize (or cache) Fibonacci numbers, as in a hash or array in Ruby.HashArray

Also: We could precompute all the needed Fibonacci values and store them in an array. Some small code modifications would be needed.

A review. This Fibonacci method uses local variables, an iterator, and a method to compute Fibonacci numbers. Its core algorithm is simple. It helps us learn how this sequence is computed.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf