How to create new functions for String class in Ruby? -
i want check type of strings encounter:
class string def is_i? /\a[-+]?\d+\z/ === self end def is_path? pn = pathname.new(self) pn.directory? end end def check(key) puts case key when is_i? puts "could number" when is_path? puts "this path" else puts "ok" end end when run check("1345425") following error:
undefined method `is_i?' main:object (nomethoderror) what should correct it?
you have defined functions on string instance, hence:
def check(key) puts case when key.is_i? "could number" when key.is_path? "this path" else "ok" end end or
def check(key) puts case key when ->(s) { s.is_i? } "could number" when ->(s) { s.is_path? } "this path" else "ok" end end upd please note removed superfluous subsequent calls puts.
Comments
Post a Comment