Random numbers in Ruby
A collection of snippets to generate random number under certain conditions, as:
- gaussian
- with a specified distribution
- triangular distribution
- ... and some more
Related cards:
SecureRandom -- Stop writing your own random number and string generators - Momoro Machine
Stop writing your own random string generators. Rails does this for you.
Ruby number formatting: only show decimals if there are any
Warning: Because of (unclear) rounding issues and missing decimal places (see examples below),
do NOT use this when dealing with money. Use our amount helper instea...
Bash: How to generate a random number within given boundaries
$RANDOM
on bash returns a random integer between 0 and 32767.
echo $RANDOM
9816
echo $RANDOM
30922
If you want to limit that to a certain maximum, you can just compare against the modulus of that maximum + 1. \
For example, the fo...
Count number of existing objects in Ruby
Sometimes you want to know exactly how many objects exist within your running Ruby process. Here is how:
stats = {}
ObjectSpace.each_object {|o| stats[o.class].nil? ? stats[o.class] = 0 : stats[o.class] += 1 }; stats
=> {String=...
Pick a random element from an array in Ruby
[1,2,3,4].sample
# => e.g. 4
If you'd like to cheat and give different weights to each element in the array, you can use the attached initializer to say:
[1,2,3,4].weighted_sample([1,1,1,1000])
# => probably 4
Lightning Talk: Coverage based Test Case Prioritization in Ruby on Rails
For my computer science bachelor's thesis I programmed and evaluated a CLI Test Case Prioritization (TCP) tool for makandra. It has been written as a Ruby Gem and was tested and evaluated against one Ruby on Rails project....
instance_eval behaves different in Ruby 1.8 and Ruby 1.9, use instance_exec instead
In Ruby 1.9, instance_eval
calls the block the with receiver as the first argument:
- In Ruby 1.8,
receiver.instance_eval(&block)
callsblock.call()
- In Ruby 1.9,
receiver.instance_eval(&block)
callsblock.call(receiver)
This will blo...
The Exciter - Why You Should Deploy Your Next Application on Ruby 1.9 and a Rant in General
The rubyforge gems model may not be perfect, but damnit people, when there’s a gem update I know that it has actually been tested somewhat and it’s not just whatever random point HEAD happens to be at, at that point in time, by some random Joe who...
Random list of ActiveSupport goodies
I recently browsed through the ActiveSupport code and found some nice stuff I did not know about:
ActiveSupport::Callbacks
-
ActiveRecord-like callback...
Ruby 2.0 Implementation Work Begins: What is Ruby 2.0 and What’s New?
While 2.0 will include a number of syntax changes, new features and general improvements, mentioned below, it is anticipated to remain backward compatible with code written for 1.9.3 and Matz has stated that the changes are less significant than t...