Flowdock

Notes posted to Ruby

RSS feed
August 3, 2015
1 thank

define_method with default parameters

To define a method with a default parameter the usual notation can be used:

define_method("example") do |fixed, default = {}|
  # something
end
July 31, 2015
0 thanks

Also takes a block

You can define methods within a block

User = Struct.new(:first_name, :last_name) do
  def full_name
    "#{first_name} #{last_name}"
  end
end

user = User.new('Simon', 'Templar') # => #<struct User first_name="Simon", last_name="Templar">
user.full_name # => "Simon Templar"
July 13, 2015
1 thank

Correction to previous comment

You’ve misread the documentation, @sandyjoins. If you pass two arguments, the second one is a length argument, not an upper bound.

“Hello there”.byteslice(6, 1) == “t”

July 13, 2015 - (v1_9_3_392)
0 thanks

Important note!

Special cases:

Code example

Test”.byteslice(1, 3) => “est” #both limits inclusive

Test”.byteslice(0, 3) => “Tes” #upper limit exclusive

Test”.byteslice(0..3) => “Test” # Both limits inclusive

May 23, 2015 - (v1_9_3_392)
0 thanks

Constants

Reading source one can find detailed patterns: github.com/ruby/ruby/blob/ruby_1_9_3/lib/uri/common.rb

May 22, 2015 - (>= v1_8_6_287)
0 thanks

Not exactly like map {}.flatten

To also give dimension, is about 4.5 times faster then map {}.flatten.

May 12, 2015
0 thanks

RE: Convert an Array of Arrays to a Hash using inject

Another way to convert an array of arrays to a hash using inject:

array = [['A', 'a'], ['B', 'b'], ['C', 'c']]

hash = array.inject({}) do |memo, values|
  memo.merge!(values.first => values.last)
end

hash
# => {'A' => 'a', 'B' => 'b', 'C' => 'c'}
May 1, 2015
7 thanks

Very bad documentation

This is terrible documentation. It makes it very hard to understand what the arguments mean.

The signature is

alias_method(p1, p2)

So what do p1 and p2 mean? The description doesn’t refer to them at all, but to new_name and old_name. How are we supposed to know which is which?

And then it gets even worse in the code sample:

alias_method :orig_exit, :exit

From the naming it sounds like the first argument is the original method name.

Documentation is supposed to resolve this kind of confusion, not create it.

April 29, 2015
0 thanks

Prevent new line character.

To prevent the “\n” character added at the end of each file pass in the “row_sep: nil” option:

[ "some", "array" ].to_csv                 # => "some, array\n"  

[ "some", "array" ].to_csv( row_sep: nil ) # => "some, array"
April 21, 2015
0 thanks

RSS feeds in Rails

Fetching RSS feeds in the request/response cycle inside a Rails application is probably not the very best approach, as it will make your application as slow as the server serving RSS feeds. Another option is to do it asynchronously using a worker or a queue, but this can also become quite complex and hard to maintain over time.

Another solution is to use an API like superfeedr.com and its Rails Engine (http://blog.superfeedr.com/consuming-rss-feeds-rails/). All the polling and parsing is done on Superfeedr’s side and your application is notified in realtime as soon as the resources are updated using a webhook pattern.

April 2, 2015
0 thanks

Typo

“Acceptable exception types maye be given as optional arguments. If the last argument is a String, it will be used as the error message.”

>

“Acceptable exception types may be given as optional arguments. If the last argument is a String, it will be used as the error message.”

March 19, 2015
0 thanks

enumerator and number of lines to read

Example

File.foreach(filename)
  .take(number_of_lines)
  .map do |line|
    # ... stuff ... 
end
March 11, 2015 - (v1_9_3_392)
0 thanks

equals a.fetch and a.at(1)

a.fetch(1) == a.at(1) #=> true

March 1, 2015
0 thanks

Not exactly like map {}.flatten

To clarify on the last comment, conceptually it’s the same, but #flat_map will perform better because there is no need to create an intermediate Array

February 24, 2015
1 thank

clarification of inputs

split(p1 = v1, p2 = v2)”

in reading the rest of the documentation, i found “p1” and “p2” to be confusing.

I think it should be:

split( pattern, limit )

February 12, 2015
0 thanks

Example is a Bug!

Why is the example showing the use of the #detect method and not #find? Boggles the mind!

January 28, 2015 - (v1_8_6_287 - v1_9_3_392)
1 thank

Feature

A default pretty printing method for general objects. It calls pretty_print_instance_variables to list instance variables.

If self has a customized (redefined) inspect method, the result of self.inspect is used but it obviously has no line break hints.

This module provides predefined pretty_print methods for some of the most commonly used built-in classes for convenience.

December 9, 2014
0 thanks

See also ConditionVariable

If you need to and processing with respect to a particular resource between 2 or more threads in more complicated ways, it is likely that ConditionVariable is what you’re looking for.

November 17, 2014
0 thanks

Elements need to be in same order

Note that even if the arrays have the same content, the elements need to be ordered:

Example:

x = [1, 2, 3]
y = [3, 2, 1]
z = [1, 2, 3]

x.eql?(y) #=> false
x.eql?(z) #=> true
x.eql?(y.sort) #=> true
March 19, 2014 - (v1_8_6_287 - v1_9_3_392)
1 thank

Right Partitioning Filename extension

1.9.3p392 :013 > x = “picture.2.jpg”

=> "picture.2.jpg" 

1.9.3p392 :015 > x.rpartition(‘.’)

=> ["picture.2", ".", "jpg"] 
February 19, 2014
0 thanks

Undocumented pile of ruby

> If you’d like to read someone’s RSS feed with your Ruby code, you’ve come to the right place


No, you’ve definitely come to wrong place. RSS is one of the worst documented libraries I’ve ever seen for Ruby. It’s as confusing and misleading as it can get.

February 4, 2014 - (v1_9_3_392)
0 thanks

Alternative to :symbol

You can also pass string as an alternative to :symbol

k = Klass.new

k.send “hello”, “gentle”, “readers” #=> “Hello gentle readers”

January 22, 2014
0 thanks

re: question?

Nope. Read it again:

> This generates a sequence of self.size n-element arrays

If any of the arguments are longer than the receiver, the elements beyond the receiver’s length are ignored

November 19, 2013
0 thanks

Return value not correct

It seems like trap returns nil if the handler was “DEFAULT”, but calling trap with nil causes a “IGNORE”

2.0.0-p247 :020 > p trap("CHLD", "DEFAULT")
nil
 => nil 
2.0.0-p247 :021 > p trap("CHLD", nil)
nil
 => nil 

So it seems that once you trap a signal, there isn’t a way to reset them back to what they were originally.

November 15, 2013
0 thanks

Test if an array is included in another

a note for anoiaque solution…

before running you need to require set

require 'set'
class Array
  def included_in? array
    array.to_set.superset(self.to_set)
  end
end

[1,2,4].included_in?([1,10,2,34,4]) #=> true
November 12, 2013
0 thanks

Be aware

Be aware

'John    Doe №88'.sqeeze 
=> 'John Doe №8' # with just one '8'
September 27, 2013
1 thank

Using find_index to return first match. Profit!

This example shows how to use find_index to return a result as soon as the first occurrence of what you are looking for is found.

Code example

class Widget < Struct.new(:name, :profit); end

class WidgetManager
  def initialize(*widgets)
    @widgets = widgets
  end
  def is_any_widget_profitable?
    @widgets.find_index { |w| w.profit > 0 }  # <== usage!
  end
end

wm = WidgetManager.new(Widget.new('a', -100), Widget.new('b', 200), Widget.new('c', 300))
wm.is_any_widget_profitable?  # => 1
(wm.is_any_widget_profitable?) ? 'some profit' : 'all loss'  # => "some profit"

wm = WidgetManager.new(Widget.new('a', -100), Widget.new('b', -200), Widget.new('c', -300))
wm.is_any_widget_profitable?  # => nil
(wm.is_any_widget_profitable?) ? 'some profit' : 'all loss'  # => "all loss"
September 25, 2013
0 thanks

Anothery way

This Worked For Me

require File.expand_path('../app/models/extenstions/active_record_ext', File.dirname(__FILE__))

I did this in application.rb

September 9, 2013
1 thank

Using reject to remove key/value pairs from a hash

Code example

# Remove empty strings
{ a: 'first', b: '', c: 'third' }.reject { |k,v| v.empty? } #=> {:a=>"first", :c=>"third"}

# Remove nil
{a: 'first', b: nil, c: 'third'}.reject { |k,v| v.nil? } # => {:a=>"first", :c=>"third"}

# Remove nil & empty strings
{a: '', b: nil, c: 'third'}.reject { |k,v| v.nil? || v.empty? } # => {:c=>"third"}
May 16, 2013
0 thanks

Bug in Ruby or this documentation

%Q doesn’t return microseconds but milliseconds! Use %s%6N for microseconds.