Secure Random passwords in Ruby

Problem
You would like to use a random password in ruby. Most solutions describe using the Digest library (Digest::SHA1).

Solution
According to the post here, you can achieve the same by using ActiveSupport’s secure_random library.
To use it in Ruby outside Rails use:

require 'active_support/secure_random'
ActiveSupport::SecureRandom.hex(10)
ActiveSupport::SecureRandom.base64(10)


and inside rails:

SecureRandom.hex(10)

replacing comma with and in a list with ruby

Problem
You have a list, usually after using join(“,”) in an array that consists of different values ie “one, two, three, four”, but you want to replace the last comma with and so it would be “one, two, three and four”.

Solution
Use reverse initially to reverse the string, then use sub to replace the last comma with the word and reversed (dna), and then finally reverse the string again.

string_with_and=string_with_commas.reverse.sub(/,/, ‘ dna ‘).reversestring_with_no_commas=array.to_sentence(options = {:last_word_connector => ” and “})

ruby incorrect encoding of pound sign(£)

Problem
You want to pass the £ sign to an http service, but the ruby CGI.escape encodes it incorrectly.

Solution
After using ruby’s CGI.escape for the string as:

sms_msg_tmp=CGI.escape(sms_code)

then replace the encoding with the pound sign encoding as in:

sms_msg=sms_msg_tmp.gsub('%C2%A3','%A3')

It should then pass the correct value for the £ sign.