Ruby String#To_Class

ruby String class: what is the % symbol a method?

It's syntax sugar. You can call it with . if you want:

"%05d" % 123
# => "00123"

is equivalent to:

"%05d".% 123
# => "00123"

A similar example:

1 * 2 + 3
# => 5
(1.*(2)).+(3)
# => 5

The second form is valid, but we usually choose the first form as it's clearer.

ruby convert class name in string to actual class

I think what you want is constantize

That's an RoR construct. I don't know if there's one for ruby core

Re-open String class and add .upcase method in Ruby

Extending core classes is fine to do so long as you're careful, especially when it comes to re-writing core methods.

Remember whenever you're inside an instance method then self always refers to the instance:

def my_special_upcase
self.upcase + '!'
end

So self refers to the string in question.

How to create new functions for String class in Ruby?

You have defined functions on String instance, hence:

def check(key)
puts case
when key.is_i?
"Could be a number"
when key.is_path?
"This is a path"
else
"Ok"
end
end

or

def check(key)
puts case key
when ->(s) { s.is_i? }
"Could be a number"
when ->(s) { s.is_path? }
"This is a path"
else
"Ok"
end
end

UPD Please also note that I removed superfluous subsequent calls to puts.

Convert string to class name without using eval in ruby?

You can try

class Post
end

Object.const_get("Post")

Which returns the Post class

Extend Ruby String class with method to change the contents

Use String#replace:

class String
def clear!
replace ""
end
end

x = "foo"
x.clear!
p x
#=> ""

Similarly available: Array#replace and Hash#replace.

Alternatively, and far less cleanly:

class String
def clear!
gsub! /.+/m, ''
end
end

class String
def clear!
slice!(0,-1)
end
end

# ...and so on; use any mutating method to set the contents to ""


Related Topics



Leave a reply



Submit