Flowdock

Notes posted to Ruby

RSS feed
December 2, 2008
5 thanks

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

http://www.ruby-doc.org/core/classes/Enumerable.html

November 20, 2008
1 thank
November 19, 2008
9 thanks

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”

November 18, 2008
9 thanks

Pop for last, Shift for first

If you want to pop the first element instead of the last one, use shift .

November 6, 2008 - (v1_8_6_287)
1 thank

Missing Documentation

Returns false if obj <=> min is less than zero or if anObject <=> max is greater than zero, true otherwise.

3.between?(1, 5)               #=> true
6.between?(1, 5)               #=> false
'cat'.between?('ant', 'dog')   #=> true
'gnu'.between?('ant', 'dog')   #=> false
November 2, 2008 - (v1_8_6_287)
1 thank

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"
October 23, 2008
1 thank

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
October 17, 2008
1 thank

Use encode64!

b64encode will print to the commandline, what a useful feature…

October 9, 2008
6 thanks

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.

October 9, 2008
1 thank

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.

October 3, 2008
0 thanks

POST DATA

post data should be separed with ‘&’ and not ‘;’

your example

req.set_form_data({'from'=>'2005-01-01', 'to'=>'2005-03-31'}, ';')

should be

req.set_form_data({'from'=>'2005-01-01', 'to'=>'2005-03-31'}, '&')

isnt it?

September 21, 2008
0 thanks

Better Description

This is really a bitshift left.

September 12, 2008
24 thanks

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”

September 10, 2008
0 thanks

Actual superclass

This class’s actual superclass is Net::HTTPRequest, for some reason that isn’t linked in here.

September 5, 2008
3 thanks

Require 'strscan'

To use the StringScanner class,

require 'strscan'
August 27, 2008 - (v1_8_6_287)
3 thanks

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>

August 23, 2008
2 thanks

Needs requiring 'enumerator' to work

This method needs that you

require 'enumerator'

for this method to be available.

August 23, 2008
0 thanks

Needs requiring 'enumerator' to work

This method needs that you

require 'enumerator'

for this method to be available.

August 23, 2008
0 thanks

Needs requiring 'enumerator' to work

This method needs that you

require 'enumerator'

for this method to be available.

August 23, 2008
0 thanks

Needs requiring 'enumerator' to work

This method needs that you

require 'enumerator'

for this method to be available.

August 23, 2008
4 thanks

Needs requiring 'enumerator' to work

This method needs that you

require 'enumerator'

for this method to be available.

August 23, 2008
2 thanks

Needs requiring 'enumerator' to work

This method needs that you

require 'enumerator'

for this method to be available.

August 23, 2008
1 thank

Needs requiring 'enumerator' to work

This method needs that you

require 'enumerator'

for this method to be available.

August 23, 2008
0 thanks

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

August 23, 2008
2 thanks

Some methods listed for this class need require 'enumerator'

The methods:

need that you put this require in your scripts:

require 'enumerator'
August 18, 2008
0 thanks

Last element of an array alternative

You can also access the last element of an array with -1

[ "w", "x", "y", "z" ][-1]  #=> "z"
August 17, 2008
6 thanks

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"]}
August 17, 2008
4 thanks

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"]
August 15, 2008
4 thanks

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?