Search
 
SCRIPT & CODE EXAMPLE
 

RUBY

ruby create class method

# class << self opens up self's singleton class, so that methods can be redefined for the current self object
class String
  class << self
    def value_of obj
      obj.to_s
    end
  end
end

String.value_of 42   # => "42"

# This can also be written as a shorthand:

class String
  def self.value_of obj
    obj.to_s
  end
end

# Even shorter
def String.value_of obj
  obj.to_s
end
Comment

call a class method ruby

class Foo
    def self.some_class_method
        puts self
    end

    def some_instance_method
        self.class.some_class_method
    end
end

print "Class method: "
Foo.some_class_method

print "Instance method: "
Foo.new.some_instance_method

Outputs:
  Class method: Foo
  Instance method: Foo
Comment

PREVIOUS NEXT
Code Example
Ruby :: rails rescue puts error 
Ruby :: Convert Date and time to utc in rails 
Ruby :: ruby debugger 
Ruby :: rails convert image to base64 
Ruby :: read xls file in ruby 
Ruby :: installing ruby version using Rbenv 
Ruby :: ruby compiler 
Ruby :: rails transactions 
Ruby :: rails content for head 
Ruby :: text_field_tag placeholder rails 
Ruby :: rails always 2 decimal 
Ruby :: input must be integer in ruby 
Ruby :: ruby for 
Ruby :: ruby lambda function 
Ruby :: ruby reduce hash 
Ruby :: ruby array loop 
Ruby :: ! in ruby 
Ruby :: insert element in the middle of an array ruby 
Ruby :: EOFError: end of file reached 
Ruby :: rails faker address 
Ruby :: start times from 1 in ruby 
Ruby :: rails format number k - m 
Ruby :: how to comment out embedded ruby 
Ruby :: save rails c output 
Ruby :: division in ruby 
R :: select columns without na in r 
R :: line split r 
R :: name elements in vector r 
R :: how to write dictionary in R 
R :: How to calculate regression line in R 
ADD CONTENT
Topic
Content
Source link
Name
1+2 =