TheRequest Interview Question’s Answer

1)
Array manipulation in Ruby

Suppose you have the following array

stuff = [:dog,:cat,:orange,:banana]
How can you slice this array to create a new array [:cat,:orange]
Add the element :apple on to the end of the array.
Now take :apple back off again
Add the element :fish to the start of the array.
Now remove the element :fish.

Solution:

def example(arr=[])
  arr = arr[1..(-2)]
  puts "1. struff=> #{arr.inspect}"
  
  arr.insert((-1), :apple)
  puts "2. struff=> #{arr.inspect}"
  
  arr.pop
  puts "3. struff=> #{arr.inspect}"
  
  arr.insert(0, :fish)
  puts "4. struff=> #{arr.inspect}"
  
  arr.shift
  puts "5. struff=> #{arr.inspect}"
  
end

example([:dog,:cat,:orange,:banana])

Output:

1. struff=> [:cat, :orange]
2. struff=> [:cat, :orange, :apple]
3. struff=> [:cat, :orange]
4. struff=> [:fish, :cat, :orange]
5. struff=> [:cat, :orange]

2)
Characters in Strings in Ruby

Implement a function with signature find_chars(string1, string2) that takes two strings and returns a string that contains only the characters found in string1 and string two in the order that they are found in string1. Implement a version of order N*N and one of order N.

Solution:

def find_chars(string1, string2)
  (string1.split('') & string2.split('')).join
end

puts find_chars("test", "string")

Output:

ts
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s