Posts in ampersand

Monday Learnings

I learned some cool things today, which I’d like to share here.

1) The each_cons method. It’s great. While working on Project Euler #11 with a friend, he showed me this method. It is applied to an array and takes an argument for n elements – it then returns an enumerator with the different variations of 3 consecutive elements from the array. I’m not sure I’m doing it justice, so here is an example:

```ruby

array = [1,2,3,4,5,6,7,8]
array.each_cons(3).to_a 3 # => [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8]]

``` This was very helpful in finding the products of each possible set of four consecutive elements (horizontally) in the problem’s grid. Nice.

written in in ampersand, methods, pry, ruby, shortcuts Read on →