Ruby 5 Good Questions

With good answers!

Ruby

Q1. Write code that splits a given array of integers into two arrays; the first containing odd numbers and second containing even numbers

Q1R1.
array.each_with_object({odd:[], even:[]}) do |elem, memo|
memo[elem.odd? ? :odd : :even] << elem
end

Q1R2. (NO DRY)
odds = array.select &:odd?
evens = array.reject &:odd?

Q2. In how many ways items can be added in an array in Ruby?

* push or <<
* unshift
* insert(int indexPosition, WhatToInsert)

Q3. In how many ways items can be removed from array in Ruby?

* pop – last element
* shift – first element
* delete – whatever you like
* uniq – remove duplicated elements

Q4. Could you list the four types of variables that provides Ruby?

* global – $GLOBALVAR – Access anywhere.
* local – _localvar – confined to the code construct within which is declared.
* class – @@classvar – shared by all instances of the class.
* instance – @instancevar – local to a single instance of a class.

Q5. Write a function that sorts the keys in a hash by the length of the key as a string. The hash: { abc: ‘hello’, ‘another_key’ => 123, 4567 => ‘third’ }

Q5R1.
hsh.keys.map(&:to_s).sort_by(&:length)

Q5R2.
hsh.keys.collect(&:to_s).sort_by { |key| key.length }