相关疑难解决方法(0)

Ruby中方法名称的限制是什么?

例如,我bundler?在以下代码段中找到了方法名称,并且不知道该?字符是专用关键字还是仅仅是方法名称的一部分.

# This is a predicate useful for the doc:guides task of applications.
def bundler?
  # Note that rake sets the cwd to the one that contains the Rakefile
  # being executed.
  File.exists?('Gemfile')
end
Run Code Online (Sandbox Code Playgroud)

ruby

44
推荐指数
2
解决办法
2万
查看次数

具有多个参数的Setter方法(赋值)

我有一个自定义类,并希望能够覆盖赋值运算符.这是一个例子:

class MyArray < Array
  attr_accessor :direction
  def initialize
    @direction = :forward
  end
end
class History
  def initialize
    @strategy = MyArray.new
  end
  def strategy=(strategy, direction = :forward)
    @strategy << strategy
    @strategy.direction = direction
  end
end
Run Code Online (Sandbox Code Playgroud)

目前这不符合预期.使用时

h = History.new
h.strategy = :mystrategy, :backward
Run Code Online (Sandbox Code Playgroud)

[:mystrategy, :backward]被分配给策略变量并且方向变量保持不变:forward.
重要的是我希望能够为direction参数分配标准值.

任何提供这项工作的线索都受到高度赞赏.

ruby

16
推荐指数
1
解决办法
4250
查看次数

标签 统计

ruby ×2