Ruby: How to make a public static method?

前端 未结 4 1908
醉梦人生
醉梦人生 2021-02-01 12:15

In Java I might do:

public static void doSomething();

And then I can access the method statically without making an instance:

c         


        
4条回答
  •  轮回少年
    2021-02-01 12:39

    Here's my copy/paste of your code into IRB. Seems to work fine.

    $ 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"
    

    Seems to work. Test it out in your irb as well, and see what results you're getting. I'm using 1.8.7 in this example, but I also tried it in a Ruby 1.9.3 session and it worked identically.

    Are you using MRI as your Ruby implementation (not that I think that should make a difference in this case)?

    In irb make a call to Ask.public_methods and make sure your method name is in the list. For example:

    1.8.7 :008 > Ask.public_methods
     => [:make_permalink, :allocate, :new, :superclass, :freeze, :===, 
         ...etc, etc.] 
    

    Since you also marked this as a ruby-on-rails question, if you want to troubleshoot the actual model in your app, you can of course use the rails console: (bundle exec rails c) and verify the publicness of the method in question.

提交回复
热议问题