SHARE
TWEET

Untitled

a guest Jul 20th, 2019 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. **Q.1 I should be able to call a method called `combine_first_and_last` on a Hash which will combine the first and last key of Hashmap. It should work for Number, String, Symbols and Arrays.**
  2.  
  3. i.e
  4.  
  5. ```
  6. { a: 2, c: 5, x: 3 } => {ax: 23, c:5}
  7.  
  8. { a: 's', c: 5, x: 'g' } => {ax: 'sg', c:'5}
  9.  
  10. { a: [1], c: 5, x: [2] } => {ax: [12], c:'5}
  11. ```
  12.  ```      
  13. def combine_first_and_last(obj)
  14.   keys = obj.keys
  15.   values = obj.values
  16.   firstkey = keys[0].to_s << keys[-1].to_s
  17.   if values[0].class == Array
  18.     firstvalue = values[0] + values[-1]
  19.   else
  20.     firstvalue = values[0].to_s + values[-1].to_s
  21.   end
  22.   obj.delete(keys[0])
  23.   obj.delete(keys[-1])
  24.   obj1={firstkey => firstvalue}.merge(obj)
  25.   return obj1
  26. end
  27. puts combine_first_and_last({ a: [1], c: 5, x: [2] })
  28. puts combine_first_and_last({ a: 's', c: 5, x: 'g' })
  29. puts combine_first_and_last({ a: 2, c: 5, x: 3 })
  30.  
  31.  ```
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top