gpt4 book ai didi

ruby - 清除实例变量的方法的命名约定

转载 作者:数据小太阳 更新时间:2023-10-29 07:59:54 25 4
gpt4 key购买 nike

什么是通过方法清除实例变量的良好命名约定。实际值存储在一个数组中,方法会过滤该数组以找到该值。

以下是我已有的方法:

class Foo

def initialize
# Array of objects
@data = []
end

# Get the variable or default value
def variable
@data.select { |o| o.attribute == 'Some Value' }.first || 'Default Value'
end

# Does the variable exist
def variable?
!!@data.select { |o| o.attribute == 'Some Value' }.first
end

# Does this make sense?
def clear_variable!
# Delete the variable
end
end

还是应该像 delete_variable! 这样的东西?

最佳答案

如果您要创建类似的东西,最好模拟在 Ruby 中最相似的结构中使用的常规方法名称。在这种情况下,它是哈希:

class Foo
def initialize
@data = [ ]
@default = 'Default Value'
end

def [](k)
found = @data.find { |o| o.attribute == k }

found ? found.value : @default
end

def has_key(k)?
!!@data.find { |o| o.attribute == k }
end

# Does this make sense?
def delete(k)
@data.reject! { |o| o.attribute == k }
end
end

通常带有 ! 的方法要么在出现问题时引发异常,要么对某物的状态进行永久修改(例如,就地修改方法),或两者兼而有之。它并不意味着“重置”或“清除”。

关于ruby - 清除实例变量的方法的命名约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23765444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com