Answer the question
In order to leave comments, you need to log in
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
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
Understood. Sobsna everything is simple:
class String
def is_wtf_string?
self == 'wtf'
end
end
a = 'wtf'
p a.is_wtf_string? #=> true
# ./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)
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
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?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question