Notes posted to Ruby

RSS feed
November 17, 2015
0 thanks

Find and Detech are the same

@rubynooby: #find and #detect are aliases of the same underlying method. You can use them interchangeably to provide additional readability to your code (find an element to use it or detect if an element is present to do something).


November 13, 2015 - (v1_9_3_125 - v1_9_3_392)
0 thanks

What you really want is

The official Ruby documentation is available for this here http://ruby-doc.org/stdlib-2.2.3/libdoc/rss/rdoc/RSS.html

But the library that will be most helpful to you is called Feedjira: http://feedjira.com/

November 3, 2015
0 thanks

Re: close but no bananna

Actually, @tarasevich is right on this. Let’s have a look at your own example:

[["1","2"],["3","4"]].flat_map {|i| i[0] }     # => ["1", "3"]

[["1","2"],["3","4"]].map {|i| i[0] }.flatten  # => ["1", "3"]
[["1","2"],["3","4"]].flatten.map {|i| i[0] }  # => ["1", "2", "3", "4"]

You are right that both #map and #flatten are non-commutative, it does matter which method is called first.

But #flat_map is equivalent to mapping first and then concatenating (flatten) the results, even if the name might suggest the opposite.

To correctly interpret the method name, you should think of it mathematically as a function composition.

November 3, 2015 - (>= v1_9_2_180)
0 thanks

close but no bananna

@tarasevich noted that

a.flat_map(&b) works exactly like a.map(&b).flatten!(1)

This is backwards because map and flatten are not always interchangeable in order. Mapping over the example array only gives you 2 items. This can result in significant differences depending on what you’re doing in the map. This is easier to demonstrate if we change the example to strings.

[["1","2"],["3","4"]].map {|i| i[0] } # => ["1", "3"]
[["1","2"],["3","4"]].map {|i| i[0] }.flatten  # => ["1", "3"]

BUT if you swap the order

[["1","2"],["3","4"]].flatten.map {|i| i[0] } # => ["1", "2", "3", "4"]

in order to remember what it is equivalent to just note that the method name is already in the correct order. flat_map -> flatten + map

September 14, 2015 - (v1_9_1_378 - v1_9_3_392)
0 thanks

Getting the return value from the underlying method of an Enumerator

This is documented in the example code, but easy to miss.

When you get an Enumerator using #to_enum(:method_name, …), you can get all of the yielded values using #next, but not the value that is finally returned.

That value can be retrieved via the #result attribute of the StopIteration exception object that is raised when calling #next after the underlying method has returned.

August 18, 2015
0 thanks

Add method to instacne eval

We can add method to instance by using instance_eval.

Code example

string = "String"
string.instance_eval do
  def new_method


irb(main):033:0> string.new_method
=> "gnirtS"
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
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}"

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

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


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)

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

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


“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


  .map do |line|
    # ... stuff ... 
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
0 thanks

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


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:


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 
2.0.0-p247 :021 > p trap("CHLD", 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.