我目前正在忙于学习Ruby和Rails,因为我有基于C语言的背景,所以Ruby的一些概念是新的,有点陌生.对我来说特别具有挑战性的是适应接近常见问题的"Ruby方式",因此我经常发现自己在Ruby中编写C语言,这不是我想要实现的.
想象一下这样的架构:
ActiveRecord::Schema.define(:version => 20111119180638) do
create_table "bikes", :force => true do |t|
t.string "Brand"
t.string "model"
t.text "description"
end
end
Run Code Online (Sandbox Code Playgroud)
该数据库已包含几种不同的自行车.我的目标是获得数据库中所有品牌的数组.
这是我的代码:
class Bike < ActiveRecord::Base
def Bike.collect_brands
temp_brands = Bike.find_by_sql("select distinct brand from bikes")
brands = Array.new
temp_brands.each do |item|
brands.push(item.brand)
end
brands
end
end
Run Code Online (Sandbox Code Playgroud)
Ruby大师如何编写代码来实现这一目标?