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
Related cards:
Ruby: How to collect a Hash from an Array
There are many different methods that allow mapping an Array to a Hash in Ruby.
Array#to_h
with a block (Ruby 2.6+)
You can call an array with a block that is called with each element. The block must return a [key, value]
tuple.
This i...
jQuery: How to remove classes from elements using a regular expression
jQuery's removeClass
removes the given class string from an element collection. If you want to remove multiple/unknown classes matching a given pattern, you can do that.
For example, consider a DOM node for the following HTML. We'll reference i...
Restangular: How to remove an element from a collection without breaking restangular
So you have a restangular collection and you want to remove an element from it, after you've successfully deleted it from the server.
The README [suggests](https://github.com/mgonto/restangular#how-do-i-ha...
Careful when calling a Ruby block with an array
When a Ruby block or proc takes multiple parameters, and you call it with an Array
, Ruby will unexpectedly splat the array elements:
block = proc { |a, b| "a=#{a}, b=#{b}" }
block.call(1, 2) # "a=1, b=2"
block.call([1, 2]) # "a=1,...
Ruby: How to grow or shrink an array to a given size
If you want to grow a Ruby Array, you might find out about #fill
but it is not really what you are looking for. [1]
For arrays of unknown size that you want to grow or shrink to a fixed size, you need to define something yourself. Like the follo...
Check that a Range covers an element in both Ruby 1.9 and 1.8.7
In order to cover some edge cases you rarely care about, Range#include?
will become very slow in Ruby 1.9:
Range#include? behaviour has changed in ruby 1.9 for non-numeric ranges. Rather...
Interacting with a Microsoft Exchange server from Ruby
Microsoft Exchange service administrators can enable Exchange Web Services (EWS) which is a rather accessible XML API for interacting with Exchange. This allows you to rea...
How to get information about a gem (via CLI or at runtime from Ruby)
When you need information about a gem (like version(s) or install path(s)), you can use the gem
binary from the command line, or the Gem
API inside a ruby process at runtime.
gem
binary (in a terminal)
You can get some information abou...
Generate a path or URL string from an array of route components
When using form_for
you can give the form's target URL either as a string or an array:
form_for(admin_user_path(@user)) do ... end
# same as:
form_for([:admin, @user]) do ... end
Same for link_to:
link_to("Label", edit_admin_u...