Skip to Content
A Common-Sense Guide to Data Structures and Algorithms
book

A Common-Sense Guide to Data Structures and Algorithms

by Jay Wengrow
August 2017
Intermediate to advanced
222 pages
5h 3m
English
Pragmatic Bookshelf
Content preview from A Common-Sense Guide to Data Structures and Algorithms

A Practical Example

Let’s say you’re tasked with writing a Ruby application that takes an array and creates a new array out of every other element from the original array. It might be tempting to use the each_with_index method available to arrays to loop through the original array as follows:

 def​ ​every_other​(array)
  new_array = []
 
  array.​each_with_index​ ​do​ |element, index|
  new_array << element ​if​ index.​even?
 end
 
 return​ new_array
 end

In this implementation, we iterate through each element of the original array and only add the element to the new array if the index of that element is an even number.

When analyzing the steps taking place here, we can see that there are really two types of steps. We have one type of ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition

A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition

Jay Wengrow

Publisher Resources

ISBN: 9781680502794Errata Page