Notes posted to Ruby
RSS feedAdd custom to config/initializers/time_formats.rb
— please delete this note; it’s rails specific —
Entries are not standalone!
The entry Pathnames consist solely of leaf filenames, so they’re not directly useable in filesystem operations like "open" or "directory?". To create a useable Pathname, append the entry onto the directory you’re iterating over.
Also keep in mind that the iteration includes the magic entries "." and "..", which you probably want to skip. (Is this true on Windows too?)
The #children method doesn’t have either of these issues, although it’s slightly less efficient since it creates an Array of Pathnames up-front instead of yielding one at a time.
Array expansion in blocks
The syntax can be improved as changing the second parameter of the block (values) and using an array of two variables instead, which will be used by Ruby as the key and value of "array".
array = [['A', 'a'], ['B', 'b'], ['C', 'c']] hash = array.inject({}) do |memo, (key, value)| memo[key] = value memo end hash # => {'A' => 'a', 'B' => 'b', 'C' => 'c'}
From 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"

