Notes posted to Ruby
RSS feedFrom the official docs
enum.inject(initial) {| memo, obj | block } => obj enum.inject {| memo, obj | block } => obj
Combines the elements of enum by applying the block to an accumulator value (memo) and each element in turn. At each step, memo is set to the value returned by the block. The first form lets you supply an initial value for memo. The second form uses the first element of the collection as a the initial value (and skips that element while iterating).
# Sum some numbers (5..10).inject {|sum, n| sum + n } #=> 45 # Multiply some numbers (5..10).inject(1) {|product, n| product * n } #=> 151200 # find the longest word longest = %w{ cat sheep bear }.inject do |memo,word| memo.length > word.length ? memo : word end longest #=> "sheep" # find the length of the longest word longest = %w{ cat sheep bear }.inject(0) do |memo,word| memo >= word.length ? memo : word.length end longest #=> 5
more info
Look at this link for more info: http://www.rubycentral.com/book/ref_m_kernel.html#Kernel.select
Formatting options
Readable strftime
%a - The abbreviated weekday name (“Sun”)
%A - The full weekday name (“Sunday”)
%b - The abbreviated month name (“Jan”)
%B - The full month name (“January”)
%c - The preferred local date and time representation
%d - Day of the month (01..31)
%H - Hour of the day, 24-hour clock (00..23)
%I - Hour of the day, 12-hour clock (01..12)
%j - Day of the year (001..366)
%m - Month of the year (01..12)
%M - Minute of the hour (00..59)
%p - Meridian indicator (“AM” or “PM”)
%S - Second of the minute (00..60)
%U - Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)
%W - Week number of the current year, starting with the first Monday as the first day of the first week (00..53)
%w - Day of the week (Sunday is 0, 0..6)
%x - Preferred representation for the date alone, no time
%X - Preferred representation for the time alone, no date
%y - Year without a century (00..99)
%Y - Year with century
%Z - Time zone name %% - Literal “%’’ character t = Time.now t.strftime(“Printed on %m/%d/%Y”) #=> “Printed on 04/09/2003” t.strftime(“at %I:%M%p”) #=> “at 08:56AM”
Pop for last, Shift for first
If you want to pop the first element instead of the last one, use shift .
The reverse operation of split is join.
Given that String#split returns an array, its reverse operation is Array#join. Example:
"life is awesome".split =>["life","is","awesome"] ["life","is","awesome"].join(" ") =>"life is awesome"
Mocking puts from RSpec
If you want to mock calls to puts from RSpec, do it from the class/module you are in:
module Foo def self.foo puts "hello" end end describe Foo do it "should write 'hello' when foo() is called" do Foo.should_receive(:puts).with("hello") # Kernel and Object don't work in this case... Foo.foo end end
Use encode64!
b64encode will print to the commandline, what a useful feature…
Ruby's exception hierarchy
Ruby’s exception hierarchy, according to http://blog.nicksieger.com/articles/2006/09/06/rubys-exception-hierarchy:
NoMemoryError ScriptError LoadError NotImplementedError SyntaxError SignalException Interrupt StandardError ArgumentError IOError EOFError IndexError LocalJumpError NameError NoMethodError RangeError FloatDomainError RegexpError RuntimeError SecurityError SystemCallError SystemStackError ThreadError TypeError ZeroDivisionError SystemExit fatal
Works with URLs too!
You can use it for web urls as well:
path, file = File.split('/uploads/art/2869-speaking-of-pic.jpg') p path # => "/uploads/art" p file # => "2869-speaking-of-pic.jpg"
And you can also use join, to merge url back from the components:
path = File.join(["/uploads/art", "2869-speaking-of-pic.jpg"]) p path # => "/uploads/art/2869-speaking-of-pic.jpg"
Using #join and #split for operations on files and path parts of the URLs is generally better than simply joining/splitting strings by ‘/’ symbol. Mostly because of normalization:
File.split('//tmp///someimage.jpg') # => ["/tmp", "someimage.jpg"] '//tmp///someimage.jpg'.split('/') # => ["", "", "tmp", "", "", "someimage.jpg"]
Same thing happens with join.
Works for URLs too
You can use it for web urls as well:
path, file = File.split('/uploads/art/2869-speaking-of-pic.jpg') p path # => "/uploads/art" p file # => "2869-speaking-of-pic.jpg"
And you can also use join, to merge url back from the components:
path = File.join(["/uploads/art", "2869-speaking-of-pic.jpg"]) p path # => "/uploads/art/2869-speaking-of-pic.jpg"
Using #join and #split for operations on files and path parts of the URLs is generally better than simply joining/splitting strings by ‘/’ symbol. Mostly because of normalization:
File.split('//tmp///someimage.jpg') # => ["/tmp", "someimage.jpg"] '//tmp///someimage.jpg'.split('/') # => ["", "", "tmp", "", "", "someimage.jpg"]
Same thing happens with join.
Better Description
This is really a bitshift left.
Readable strftime
%a - The abbreviated weekday name (“Sun”)
%A - The full weekday name (“Sunday”)
%b - The abbreviated month name (“Jan”)
%B - The full month name (“January”)
%c - The preferred local date and time representation
%d - Day of the month (01..31) %H - Hour of the day, 24-hour clock (00..23)
%I - Hour of the day, 12-hour clock (01..12)
%j - Day of the year (001..366)
%m - Month of the year (01..12) %M - Minute of the hour (00..59)
%p - Meridian indicator (“AM” or “PM”)
%S - Second of the minute (00..60)
%U - Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)
%W - Week number of the current year, starting with the first Monday as the first day of the first week (00..53)
%w - Day of the week (Sunday is 0, 0..6)
%x - Preferred representation for the date alone, no time
%X - Preferred representation for the time alone, no date
%y - Year without a century (00..99) %Y - Year with century
%Z - Time zone name %% - Literal “%” character t = Time.now t.strftime(“Printed on %m/%d/%Y”) #=> “Printed on 04/09/2003” t.strftime(“at %I:%M%p”) #=> “at 08:56AM”
Actual superclass
This class’s actual superclass is Net::HTTPRequest, for some reason that isn’t linked in here.
Example of raising a custom exception
Create custom exception<br> <pre> class PersonalException < Exception end </pre>
Raise the exception<br> <pre> raise PersonalException.new, “message” </pre>
Needs requiring 'enumerator' to work
This method needs that you
require 'enumerator'
for this method to be available.
Needs requiring 'enumerator' to work
This method needs that you
require 'enumerator'
for this method to be available.
Needs requiring 'enumerator' to work
This method needs that you
require 'enumerator'
for this method to be available.
Needs requiring 'enumerator' to work
This method needs that you
require 'enumerator'
for this method to be available.
Needs requiring 'enumerator' to work
This method needs that you
require 'enumerator'
for this method to be available.
Needs requiring 'enumerator' to work
This method needs that you
require 'enumerator'
for this method to be available.
Needs requiring 'enumerator' to work
This method needs that you
require 'enumerator'
for this method to be available.
Adds new methods to Object and Enumerable
For using this class you need
require 'enumerator'
Which also adds this methods to Object:
-
to_enum
-
enum_for
And this other methods to Enumerable:
-
each_slice
-
enum_slice
-
each_cons
-
enum_cons
-
enum_with_index
Some methods listed for this class need require 'enumerator'
The methods:
need that you put this require in your scripts:
require 'enumerator'
Last element of an array alternative
You can also access the last element of an array with -1
[ "w", "x", "y", "z" ][-1] #=> "z"
Re: Convert an Array of Arrays to a Hash using inject
If you’re sure you have a two-level array (no other arrays inside the pairs) and exactly two items in each pair, then it’s faster and shorter to use this:
array = [['A', 'a'], ['B', 'b'], ['C', 'c']] hash = Hash[*array.flatten]
For more than two-level deep arrays this will give the wrong result or even an error (for some inputs).
array = [['A', 'a'], ['B', 'b'], ['C', ['a', 'b', 'c']]] hash = Hash[*array.flatten] # => {"A"=>"a", "B"=>"b", "C"=>"a", "b"=>"c"}
But if you’re running Ruby 1.8.7 or greater you can pass an argument to Array#flatten and have it flatten only one level deep:
# on Ruby 1.8.7+ hash = Hash[*array.flatten(1)] # => {"A"=>"a", "B"=>"b", "C"=>["a", "b", "c"]}
Regexes with groups and split
When you use a Regex with capture groups, all capture groups are included in the results (interleaved with the “real” results) but they do not count for the limit argument.
Examples:
"abc.,cde.,efg.,ghi".split(/.(,)/) => ["abc", ",", "cde", ",", "efg", ",", "ghi"] "abc.,cde.,efg.,ghi".split(/(.)(,)/) => ["abc", ".", ",", "cde", ".", ",", "efg", ".", ",", "ghi"] "abc.,cde.,efg.,ghi".split(/(.(,))/) => ["abc", ".,", ",", "cde", ".,", ",", "efg", ".,", ",", "ghi"] "abc.,cde.,efg.,ghi".split(/(.(,))/, 2) => ["abc", ".,", ",", "cde.,efg.,ghi"] "abc.,cde.,efg.,ghi".split(/(.(,))/, 3) => ["abc", ".,", ",", "cde", ".,", ",", "efg.,ghi"]
Cheking if a number is prime?
It’s a class for generating an enumerator for prime numbers and traversing over them.
It’s really slow and will be replaced in ruby 1.9 with a faster one.
Note: if you just want to test whether a number is prime or not, you can use this piece of code:
class Fixnum def prime? ('1' * self) !~ /^1?$|^(11+?)\1+$/ end end 10.prime?