A
A
Alexander Grishin2016-08-30 16:05:58
Ruby on Rails
Alexander Grishin, 2016-08-30 16:05:58

How to add method (extend class) to native class object in Ruby?

I want to do the following:

class Hash < Hash
  def valid_json?(json)
    begin
      JSON.parse(json)
      return true
    rescue JSON::ParserError => e
      return false
    end
  end
end

a = Hash.new()

a = {'a'=>'n'}

puts a.valid_json? #=> true

How right?
Or this example:
class String
  def is_wtf_string?(str)
    str=='wtf' ? true : false
  end
end

a = String.new
a = 'wtf'
p a.is_wtf_string? #=> true

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Grishin, 2016-08-31
@beerdy

Understood. Sobsna everything is simple:

class String
  def is_wtf_string?
    self == 'wtf'
  end
end
a = 'wtf'
p a.is_wtf_string? #=> true

#update Alexander Shvaykin suggested that it would be better this way:
# ./ExtStandartClass.rb
module ExtString 
  def is_wtf_string?
    self == 'wtf'
  end
end

module ExtFixnum
  def squared
    self*self
  end
end

# добавим расширенные методы
class String; include ExtString; end
class Fixnum; include ExtFixnum; end


# ./SomeCode.rb
# include 'ExtStandartClass.rb'
# ...
a = 'wtf'
p a.is_wtf_string? #=> true
# ...
# где нибудь в коде если приспичит узнать что откуда
p a.method(:to_s) 
p a.method(:is_wtf_string?)
# аналогично
b = 5
p b.squared
p b.method(:to_s) 
p b.method(:squared)

A
Alexander Shvaikin, 2016-08-30
@shurik_sh

Good afternoon.
There is no need to make such a method in the Hash class, because any hash is valid json
Example:

a = {'a'=>'n'}
a.to_json #=> Валидная строка в формате json

You can, but I do not recommend adding methods to ruby ​​classes, create your own and work with it, you can inherit your class from Hash and do whatever you want with it
class MyHash < Hash

  def foo_value?
    has_value? 'foo'
  end

end

a = MyHash.new
a[:a] = 'foo'
b = MyHash.new
b[:a] = 'baz'
p a.foo_value?
p b.foo_value?

Just working with code where there are a lot of changes in standard classes is not convenient.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question