下面是对 Rails Interview Questions 中的
Ruby 部分的解答:
从上面可以看出,其实Proc和lambda都是 Proc 对象。
首先我们来回答第一问:怎么通过某个字段来对对象数组排序?
假设我们有一个对象数组 @users ,我们需要让他对字段 name 排序,则我们可以:
如果是在 ActiveRecord 中,则我们只需:
下面列举我喜欢的几个常用的gems及它的可替代备选方案
首先我们说明一下递归(recursive)和迭代(iterative):
递归 :一个树结构,每个分支都探究到最远,发现无法继续走的时候往回走,每个节点只会访问一次。
迭代 :一个环结构,每次迭代都是一个圈,不会落掉其中的每一步,然后不断循环每个节点都会被循环访问。
由此我们可以看出 ruby 中更加常用的选择是 迭代 ,就像 .each , .times , .map 等都是迭代循环的形式。
ruby之父,松本行弘,日本人
于 2015-03-20
首先用一个在Rails开发中一定会遇到的YAML文件——database.yml——作为示例。在你创建一个Rails工程后,Rails会自动给你创建一个这样的文件,它的路径是config/database.yml:# MySQL (default setup). Versions 4.1 and 5.0 are recommended.
# 此处省略一些注释。
development:
adapter: mysql
database: demo_development
username: root
password:
host: localhost
# Warning: The database defined as 'test' will be erased and
# re-generated from your development database when you run 'rake'.
# Do not set this db to the same as development or production.
test:
adapter: mysql
database: demo_test
username: root
password:
host: localhost
production:
adapter: mysql
database: demo_production
username: root
password:
host: localhost
private 方法不能有接受方即通过 对象名.方法名 来调用私有方法是行不通的,不过可以在Test类或其子类的方法中调用该私有方法(直接写方法名才行)
如:
class Test
def method1#默认为公有方法
…
end
protected #保护方法
def method2
…
end
private #私有方法
def method3
end
end
class Mytest <Test
def test_private()
method3 #正确,可以访问父类对象的私有方法
end
end
class OtherTest(注意它不是Test的子类)
def test_protected(arg) #arg是Test类的对象
arg.method2 #正确,保护方法可以把Test类或Test类的子类作为接受方
end
obg1 = Test.new
obg2 = Mytest.new
obg3 = OtherTest.new
obg3.test_protected(obg1) #正确
obg3.test_protected(obg2) #正确