Ruby 5 Good Questions

With good answers!


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

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

Q1R2. (NO DRY)
odds = &: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’ }


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