# 2016.12.07 Note

### Method Enumerable::each_cons

This method is pretty cool can help you get the consecutive n element, but remember add a to_s method if you want to make the return value as array.

Iterates the given block for each array of consecutive <n> elements. If no block is given, returns an enumerator.

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

### Method Float::ceil

Returns the smallest Integer greater than or equal to float.

`1.2.ceil # => 22.0.ceil # => 2(-1.2).ceil #=> -1`

### Convert octal to decimal

This is one of the exercise in weekly challenge, I would like to record this exercise and explain it

It we got an octal number 233,basically we have to do following calculation to convert it to be decimal

`  233 #octal= 2*8^2 + 3*8^1 + 3*8^0= 2*64  + 3*8   + 3*1= 128   + 24    + 3= 155 #decimal`

Let’s write a method to do it, let’s name the method as to_decimal

`def to_decimal(oct_num)  oct_num.chars.reduce(0) { |sum, value| (sum + value.to_i) * 8} / 8end`

At first we use chars to turn string into array, which is like

`"233".chars => ["2", "3", "3"]`

Then we can make good use of the reduce method to help us to turn the octal to decimal. The logic here is while reduce iterate through each element, the sum of sum and the value will multiply 8 every time. And the first digit will be multiplied (string.size -1) times, second digit is (string.size-2) and the last digit will be multiplied once. But the result will be slightly different from what we expected, cause every digit is multiplied 1 more time. So that is why the return need to divide 8.

Actually we can use another method, but that one is bit slower, the code is below:

`def to_decimal(string)  string.map(&:to_i)               .reverse             .map.with_index{ |digit, index| digit * (8 ** index) }          .inject(:+)end`

### Summary

Honestly, I felt upset about my learning speed, so I would like to optimize my learning strategy and speed up.

Like what you read? Give JiaHung Lin a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.