Ruby function to remove all white spaces?
If you want to remove only leading and trailing whitespace (like PHP’s trim) you can use .strip, but if you want to remove all whitespace, you can use .gsub(/\s+/, “”) instead .
If you want to remove only leading and trailing whitespace (like PHP’s trim) you can use .strip, but if you want to remove all whitespace, you can use .gsub(/\s+/, “”) instead .
Using scan should do the trick: string.scan(/regex/)
Are you looking for the following? File.open(yourfile, ‘w’) { |file| file.write(“your text”) }
Yes, it’s called next. for i in 0..5 if i < 2 next end puts “Value of local variable is #{i}” end This outputs the following: Value of local variable is 2 Value of local variable is 3 Value of local variable is 4 Value of local variable is 5 => 0..5
Hash‘s key? method tells you whether a given key is present or not. session.key?(“user”)
(0…8).map { (65 + rand(26)).chr }.join I spend too much time golfing. (0…50).map { (‘a’..’z’).to_a[rand(26)] }.join And a last one that’s even more confusing, but more flexible and wastes fewer cycles: o = [(‘a’..’z’), (‘A’..’Z’)].map(&:to_a).flatten string = (0…50).map { o[rand(o.length)] }.join If you want to generate some random text then use the following: 50.times.map { … Read more
#!/usr/bin/env ruby =begin Every body mentioned this way to have multiline comments. The =begin and =end must be at the beginning of the line or it will be a syntax error. =end puts “Hello world!” <<-DOC Also, you could create a docstring. which… DOC puts “Hello world!” “..is kinda ugly and creates a String instance, … Read more
You can use the include? method: my_string = “abcdefg” if my_string.include? “cde” puts “String includes ‘cde'” end
%w(foo bar) is a shortcut for [“foo”, “bar”]. Meaning it’s a notation to write an array of strings separated by spaces instead of commas and without quotes around them. You can find a list of ways of writing literals in zenspider’s quickref.
TL;DR: Use StandardError instead for general exception catching. When the original exception is re-raised (e.g. when rescuing to log the exception only), rescuing Exception is probably okay. Exception is the root of Ruby’s exception hierarchy, so when you rescue Exception you rescue from everything, including subclasses such as SyntaxError, LoadError, and Interrupt. Rescuing Interrupt prevents … Read more