Setting primary key from hash

Mange Mar 24, 2010 1 thank

If you try to specify the value for your primary key (usually "id") through the attributes hash, it will be stripped out:

Post.new(:id => 5, :title => 'Foo') #=> #<Post @id=nil @title="Foo">

You can solve this by setting it directly, perhaps by using a block:

Post.new(:title => "Foo") {...

collect_with_index

noniq Mar 18, 2010 3 thanks

Use Object#enum_for if you need to collect with index:

require 'enumerator'

['a', 'b', 'c'].enum_for(:each_with_index).collect do |item, index| 
"#{index}: #{item}" 
end

See also: Enumerable#each_with_index

collect_with_index

noniq Mar 18, 2010

Use Object#enum_for if you need to collect with index:

require 'enumerator'

%w{foo bar}.enum_for(:each_with_index).collect do |item, index| 
"#{index}: #{item}" 
end

See also: Enumerable#each_with_index

Create new Hash as subset of another a different way

sfusion Mar 17, 2010

or

only keys old_hash = { :a => 'A', :b => 'B', :c => 'C', :d => 'D', :e => 'E', :f => 'F' } only_keys = [ :a, :c, :f ] new_hash = old_hash.delete_if { |k, v| !only_keys.include? k }

only values old_hash = { :a => 'A', :b => 'B', :c => 'C', :d => 'D', :e => 'E', :f => 'F' } onl...

Create new Hash as subset of another

guyboertje Mar 17, 2010

old_hash = {:a=>'A',:b=>'B',:c=>'C',:d=>'D',:e=>'E',:f=>'F'}

only_keys = [:a,:c,:f]

new_hash = Hash[*old_hash.find_all{|k,v| only_keys.member?(k)}.flatten]

=> {:a=>"A", :c=>"C", :f=>"F"}

or for values

only_vals = ['A','D','G']

new_hash = Hash[*old_hash.find_all{|k,v| only_vals.member?(v)}....

Complete Formatting Codes

mindloaf Mar 12, 2010

%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

%C - Century (20 in 2009)

%d - Day of the month (01..31)

%D - Date (%m/%d/%y...

Complete Formatting Codes

mindloaf Mar 12, 2010 3 thanks

NOTE: Some of these seem only to work for DateTime (e.g. %L, %N)

%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

%C - Centu...

Use message param

szeryf Mar 11, 2010

The +message+ param is invaluable in case test fails -- if you use it to display relevant info, you will find out what went wrong much faster.

Reworking the silly example above:

assert some_list.include?(5)

will only tell you that

<false> is not true.

which isn't terribly helpful, is it...

Available statuses

szeryf Mar 11, 2010 3 thanks

All the available statuses (extracted from +SYMBOL_TO_STATUS_CODE+ hash) in a slightly more readable form:

:continue                        => 100
:switching_protocols             => 101
:processing                      => 102
:ok                              => 200
:created...