为什么我们使用符号作为参数?
Why do we use symbols as parameters?
型号:
class Tweet < ActiveRecord::Base
has_one :location, dependent: :destroy
end
class Location < ActiveRecord::Base
belongs_to :tweet
end
控制器:
class TweetsController < ApplicationController
def index
@tweets = Tweet.recent.includes(:location)
end
end
为什么我们在ruby中使用符号(:location
)作为参数?
为什么这不起作用?
@tweets = Tweet.recent.includes(location)
因为您传递的本质上是一个字符串,活动记录将使用该字符串来构建 sql 查询。没有冒号的位置将是一个局部变量。我们可能会传递一个 class (位置),但符号对于 ActiveRecord 目的更有效。符号是一个不可变的字符串,本质上是一种指向字符串的指针,因此非常有效。
通常使用散列作为参数传递给方法,因为这样您就不必担心参数的顺序。此外,经常用于可选参数。考虑以下示例:
def method_with_args(name, age, dollar_amount, occupation) # gets sort of ugly and error prone
# do something with args
end
def method_with_hash(hash = {}) # cleans up ordering and forces you to 'name' variables
name = hash[:name]
age = hash[:age]
dollar_amount = hash[:dollar_amount]
occupation = hash[:occupation]
# do stuff with variables
end
你问题的第二部分:
@tweets = Tweet.recent.includes(location)
这里的location应该定义为调用方法的对象上的变量或方法。如果您 运行 代码,错误将提示您该信息。
就哈希访问和性能而言:对哈希的符号访问速度大约快 2 倍。字符串访问每次实例化时都会将字符串分配给内存,这会创建大量垃圾对象。看看这个 blog post
型号:
class Tweet < ActiveRecord::Base
has_one :location, dependent: :destroy
end
class Location < ActiveRecord::Base
belongs_to :tweet
end
控制器:
class TweetsController < ApplicationController
def index
@tweets = Tweet.recent.includes(:location)
end
end
为什么我们在ruby中使用符号(:location
)作为参数?
为什么这不起作用?
@tweets = Tweet.recent.includes(location)
因为您传递的本质上是一个字符串,活动记录将使用该字符串来构建 sql 查询。没有冒号的位置将是一个局部变量。我们可能会传递一个 class (位置),但符号对于 ActiveRecord 目的更有效。符号是一个不可变的字符串,本质上是一种指向字符串的指针,因此非常有效。
通常使用散列作为参数传递给方法,因为这样您就不必担心参数的顺序。此外,经常用于可选参数。考虑以下示例:
def method_with_args(name, age, dollar_amount, occupation) # gets sort of ugly and error prone
# do something with args
end
def method_with_hash(hash = {}) # cleans up ordering and forces you to 'name' variables
name = hash[:name]
age = hash[:age]
dollar_amount = hash[:dollar_amount]
occupation = hash[:occupation]
# do stuff with variables
end
你问题的第二部分:
@tweets = Tweet.recent.includes(location)
这里的location应该定义为调用方法的对象上的变量或方法。如果您 运行 代码,错误将提示您该信息。
就哈希访问和性能而言:对哈希的符号访问速度大约快 2 倍。字符串访问每次实例化时都会将字符串分配给内存,这会创建大量垃圾对象。看看这个 blog post