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
Detect Number of Cpus Installed
Only Show Decimal Point If Floating Point Component Is Not .00 Sprintf/Printf
How to Avoid Duplicates in a Has_Many :Through Relationship
In Ruby, What Structures Can a 'Rescue' Statement Be Nested In
Check If User Is Active Before Allowing User to Sign in with Devise (Rails)
Error Installing Homebrew - Brew Command Not Found
Setting Request Headers in Ruby
Make Rake Task from Gem Available Everywhere
Why Does Ruby Open-Uri's Open Return a Stringio in My Unit Test, But a Fileio in My Controller
Installing Rails: "File Not Found: Lib"
Seeding File Uploads with Carrierwave, Rails 3
Ruby: Finding Most Recently Modified File
Error While Installing Ruby-1.8.7 on Fedora 15
Rake Aborted, Error While Trying to Load the Gem 'Uglifier'