Tom*_*Tom 62 ruby ruby-on-rails
在Java中我可能会这样做:
public static void doSomething();
然后我可以静态访问该方法而无需创建实例:
className.doSomething(); 
我怎么能在Ruby中做到这一点?这是我的课程,根据我的理解self.,该方法是静态的:
class Ask
  def self.make_permalink(phrase)
    phrase.strip.downcase.gsub! /\ +/, '-'
  end
end
但是当我试着打电话时:
Ask.make_permalink("make a slug out of this line")
我明白了:
undefined method `make_permalink' for Ask:Class
如果我没有声明该方法是私有的,为什么呢?
dev*_*and 98
您给出的示例运行良好
class Ask
  def self.make_permalink(phrase)
    phrase.strip.downcase.gsub! /\ +/, '-'
  end
end
Ask.make_permalink("make a slug out of this line")
我在1.8.7和1.9.3中尝试过您的原始脚本中是否有拼写错误?
祝一切顺利
Iva*_*rov 18
还有一种语法可以添加更多静态方法
class TestClass
  # all methods in this block are static
  class << self
    def first_method
      # body omitted
    end
    def second_method_etc
      # body omitted
    end
  end
  # more typing because of the self. but much clear that the method is static
  def self.first_method
    # body omitted
  end
  def self.second_method_etc
    # body omitted
  end
end
这是我将代码复制/粘贴到IRB中.似乎工作正常.
$ irb
1.8.7 :001 > class Ask
1.8.7 :002?>   
1.8.7 :003 >   def self.make_permalink(phrase)
1.8.7 :004?>     phrase.strip.downcase.gsub! /\ +/, '-'
1.8.7 :005?>   end
1.8.7 :006?>   
1.8.7 :007 > end
 => nil 
1.8.7 :008 > Ask.make_permalink("make a slug out of this line")
 => "make-a-slug-out-of-this-line"
似乎工作.在你的测试中irb,看看你得到了什么结果.我在这个例子中使用的是1.8.7,但我也在Ruby 1.9.3会话中尝试过,它的工作方式相同.
你是否使用MRI作为你的Ruby实现(不是我认为在这种情况下应该有所作为)?
在irb拨打电话Ask.public_methods并确保您的方法名称在列表中.例如:
1.8.7 :008 > Ask.public_methods
 => [:make_permalink, :allocate, :new, :superclass, :freeze, :===, 
     ...etc, etc.] 
由于您还将此标记为ruby-on-rails问题,如果您要对应用中的实际模型进行故障排除,您当然可以使用rails console :( bundle exec rails c)并验证相关方法的公开性.
| 归档时间: | 
 | 
| 查看次数: | 61194 次 | 
| 最近记录: |