How to generate a random string in Ruby

(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

Multi-Line Comments in Ruby?

#!/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

What does %w(array) mean?

%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.

Why is it bad style to `rescue Exception => e` in Ruby?

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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)