Ruby面试题

2015-11-29  本文已影响3491人  Kjiang

下面是对Rails Interview Questions中的
Ruby部分的解答:

1 What's the difference between a lambda, a block and a proc?

(1)Blocks与Procs的不同点

(2)Proc和Lambda的异同

proc = Proc.new {puts "hello world"}
lambda = lambda {puts "hello world"}

proc.class  # rerturn 'Proc'
lambda.class # return 'Proc'

从上面可以看出,其实Proc和lambda都是Proc对象。

lam = lambda { |x| puts x}
lam.call(2)  # print 2
lam.call  # ArgumentError: wrong number of arguments (0 for 1)
lam.call(1,2) # ArgumentError: wrong number of arguments (2 for 1)

pro = Proc.new {|x| puts x}
proc.call(2)  # print 2
proc.call    # return nil
proc.call(1,2) # print 1
def lambda_test
  lam = lambda { return }
  lam.call
  puts "hello"
end

lambda_test   # puts 'hello'

def proc_test
  pro = Proc.new {return}
  proc.call
  puts 'hello'
end

proc_test  # return nil  不打印hello

2 How do you sort an Array of objects by paticular attributes? What is better way to do sorting with ActiveRecord?

首先我们来回答第一问:怎么通过某个字段来对对象数组排序?
假设我们有一个对象数组@users,我们需要让他对字段name排序,则我们可以:

@users.sort!{|a,b| a.name <=> b.name}

如果是在ActiveRecord中,则我们只需:

@users = @users.order(:name)

3 What are some of your favorite gems? What are their alternatives?

下面列举我喜欢的几个常用的gems及它的可替代备选方案

4 In Ruby, which is generally the better option: a recursive function or an iterative one?

首先我们说明一下递归(recursive)和迭代(iterative):

递归:一个树结构,每个分支都探究到最远,发现无法继续走的时候往回走,每个节点只会访问一次。

迭代:一个环结构,每次迭代都是一个圈,不会落掉其中的每一步,然后不断循环每个节点都会被循环访问。

由此我们可以看出ruby中更加常用的选择是迭代,就像.each,.times,.map等都是迭代循环的形式。

5 What are #method_missing and #send? Why are they useful?

class Legislator
  # Pretend this is a real implementation
  def find(conditions = {})
  end
  
  # Define on self, since it's  a class method
  def self.method_missing(method_sym, *arguments, &block)
    # the first argument is a Symbol, so you need to_s it if you want to pattern match
    if method_sym.to_s =~ /^find_by_(.*)$/
      find($1.to_sym => arguments.first)
    else
      super
    end
  end
end
class Box
  def open_1
    puts "open box"
  end

  def open_2
    puts "open lock and open box"
  end

  def open_3
    puts "It's a open box"
  end

  def open_4
    puts "I can't open box"
  end

  def open_5
    puts "Oh shit box!"
  end 
end

box = Box.new

box.send("open_#{num}")

6 What are the various Ruby runtimes, and how are they different?

7 Define "Matz"

ruby之父,松本行弘,日本人

参考文档

于 2015-03-20

上一篇 下一篇

猜你喜欢

热点阅读