Notes posted to Ruby
RSS feedOUTDATED!!!
Man, this stuff is so outdated. Be very careful using anything from here. A lot has changed since Ruby 1.9.
You’ll want to look at the updated docs, like here for Ruby 2.5.1:
ruby-doc.org/core-2.5.1/Time.html#method-i-strftime
They really should just take this site down if they’re not going to keep it updated. Probably does more harm than good now.
define_method with blocks works differently
As it is already stated that block is evaluated using instance_exec/instance_eval, so let me give you an example.
module Service module ClassMethods def endpoint_instance_exec(name, &block) define_method name do instance_exec(&block) end end def endpoint_block_call(name, &block) define_method name, &block end def endpoint_block_improper_call(name, &block) define_method name do # In this case, we called the block without "instance_eval" that # means block was called in the context of class MyService. block.call end end end def self.included(klass) klass.extend ClassMethods end private def hello puts 'world' end end class MyService include Service endpoint_instance_exec :foo do hello end endpoint_block_call :bar do hello end endpoint_block_improper_call :foobar do hello end end
Now, understand how can we execute the code and understand the working of define_method and instance_exec.
MyService.new.foo # => "hello" MyService.new.bar # => "hello" MyService.new.foobar # => undefined local variable or method `hello' for MyService:Class
Urlify Functions & Its Implementation
URLify is a simple gem that refines the conversion of UTF-8 strings to ASCII-safe URI strings and enables it to be used as readable URL-segments. After the gem is installed, you can call the URLify function for any UTF-8 string and it will be automatically converted into an ASCII-safe URI string. URLify also has the additional functionality of being able to remove the subtitles in a given input. ACCENTMAP
‘À’ => ‘A’, ‘Á’ => ‘A’, ‘Â’ => ‘A’, ‘Ã’ => ‘A’, ‘Ä’ => ‘A’, ‘Å’ => ‘AA’, ‘Æ’ => ‘AE’, ‘Ç’ => ‘C’, ‘È’ => ‘E’, ‘É’ => ‘E’, ‘Ê’ => ‘E’, ‘Ë’ => ‘E’, ‘Ì’ => ‘I’, ‘Í’ => ‘I’, ‘Î’ => ‘I’, ‘Ï’ => ‘I’, ‘Ð’ => ‘D’, ‘Ł’ => ‘L’, ‘Ñ’ => ‘N’, ‘Ò’ => ‘O’, ‘Ó’ => ‘O’, ‘Ô’ => ‘O’, ‘Õ’ => ‘O’, ‘Ö’ => ‘O’, ‘Ø’ => ‘OE’, ‘Ù’ => ‘U’, ‘Ú’ => ‘U’, ‘Ü’ => ‘U’, ‘Û’ => ‘U’, ‘Ý’ => ‘Y’, ‘Þ’ => ‘Th’, ‘ß’ => ‘ss’, ‘à’ => ‘a’, ‘á’ => ‘a’, ‘â’ => ‘a’, ‘ã’ => ‘a’, ‘ä’ => ‘a’, ‘å’ => ‘aa’, ‘æ’ => ‘ae’, ‘ç’ => ‘c’, ‘è’ => ‘e’, ‘é’ => ‘e’, ‘ê’ => ‘e’, ‘ë’ => ‘e’, ‘ì’ => ‘i’, ‘í’ => ‘i’, ‘î’ => ‘i’, ‘ï’ => ‘i’, ‘ð’ => ‘d’, ‘ł’ => ‘l’, ‘ñ’ => ‘n’, ‘ń’ => ‘n’, ‘ò’ => ‘o’, ‘ó’ => ‘o’, ‘ô’ => ‘o’, ‘õ’ => ‘o’, ‘ō’ => ‘o’, ‘ö’ => ‘o’, ‘ø’ => ‘oe’, ‘ś’ => ‘s’, ‘ù’ => ‘u’, ‘ú’ => ‘u’, ‘û’ => ‘u’, ‘ū’ => ‘u’, ‘ü’ => ‘u’, ‘ý’ => ‘y’, ‘þ’ => ‘th’, ‘ÿ’ => ‘y’, ‘ż’ => ‘z’, ‘Œ’ => ‘OE’, ‘œ’ => ‘oe’, ‘&’ => ‘and’
Easy Steps To Implement URLify Gem
Go to the Gemfile and add the gem urlify Run the command bundle install
OR In the terminal, run the command gem install urlify A Demo Of Implementation Of URLify
Here is an example of URLify functionality:
Add gem urlify in your Gemfile Run bundle install
Read More From Here http://www.railscarma.com/blog/technical-articles/urlify-functions-implementation/
Faker Gem: Fake Data Generation in Ruby
Gems are libraries in Rails that generally enable you to write the application code faster and thereby making a great product in far lesser time. Usually, whenever we start developing any application, there comes a point when we need data which we can use to see how the application will behave while doing some load testing or how it would look when we deploy it to the production. The manual process of creating the data can be daunting. Faker gem serves to take this pain away by generating the fake data just as needed and saving us all the time and effort otherwise wasted in the manual process of data-generation.
It can generate almost any kind of data suitable for our application. For example, it can generate the fake data for fields such as name, email, passwords, phone-numbers, paragraphs, etc. It is therefore, an awesome way of populating the model (which is a database layer in Rails)
Let’s take a look at this gem by creating a sample project. Read More: http://www.railscarma.com/blog/technical-articles/faker-gem-fake-data-generation-ruby/
And yet another way to get relative path from absolute globbing
If you execute glob within a block passed to Dir.chdir, you get the paths relative to the directory specified by Dir.chdir… like this…
base_dir = '/path/to/dir' files = Dir.chdir(base_dir) do Dir.glob("**/*.yml") end files.first # => 'foo/bar.yml'
nope
If you pass nil as local file, it doesn’t write the file and only returns the content as string.
Sort Integers
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin16]
Sort From Greatest to Smallest
>> [1, 2, 3, 4].sort { |a, z| z <=> a } => [4, 3, 2, 1]
Clarifying the confusing example
since exit is a keyword in Ruby, the example may be confusing. The following example might be less so:
module Foo begin # this raises an error b/c baz is not defined here alias_method :other_baz, :baz rescue NameError =>e puts e end def baz puts "first baz called" end # now that baz method is defined, we can define an alias alias_method :other_baz, :baz # we can now overwrite baz. # If we want the original baz, use the alias we just defined def baz puts "second baz called" end def qux puts "qux called" end alias_method :bar, :qux end include Foo # calls the second baz method, b/c it overwrites the first baz #=> "second baz called" # calls the first baz method, due to the alias_method making a copy other_baz #=> "first baz called" bar #=> "qux called" qux #=> "qux called"
The resulting output is:
undefined method `baz' for module `Foo' second baz called first baz called qux called qux called
Rails caching with dalli gem
Dalli is a high performance pure Ruby client for accessing memcached servers. It works with memcached 1.4+ only, as it uses the newer binary protocol.
Memcache Memcached is a quick in-memory protest reserving framework that can make Rails run much quicker with not very many changes. Memcached is an in-memory key-value store for little pieces of discretionary information (strings, objects) from consequences of database calls, API calls, or page rendering.
Run the command below to install memcached On Ubuntu
sudo apt-get install memcached
On Mac
brew install memcached
Please refer the URL below to know more about installing memcahed
https://github.com/petergoldstein/dalli#installation-and-usage Install dalli gem gem 'dalli'
Add the gem above to your gemfile and run bundle install.
Configuration Here, we have to configure our rails app to serve caching mechanisam. Add below line to the production.rb(config/environments/production.rb)
config.cache_store = :dalli_store Dalli::Client accepts the following options. All times are in seconds.
expires_in: Global default for key TTL. Default is 0, which means no expiry. namespace: By default, it is nil. It’s prepend to each key if you specify namespace. failover: Default is true. Boolean, if true, Dalli will failover to another working server if the main server for a key is down. threadsafe: Boolean. If true, Dalli ensures that only one thread is using a socket at a specified given time. Default is true. serializer: The serializer to use for objects being stored (ex. JSON). Default is Marshal. compress: Boolean, if true Dalli will gzip-compress values larger than 1K. Default is false. compression_min_size: Minimum value byte size for which to attempt compression. Default is 1K. compression_max_size: Maximum value byte size for which to attempt compression. Default is unlimited. Please check more configations at
https://github.com/petergoldstein/dalli#configuration
After this, we have to tell ActionController to perform caching. Add the line below to the same file and restart Rails server if you are already running it.
config.action_controller.perform_caching = true
Please add the code below to your index method
@posts = Rails.cache.fetch('posts', expires_in: 5.minutes){ Post.all }
Here, Rails.catche.fetch reads the data from ‘posts’ key. If the specified key has any data, it will return data otherwise it will write to that key and it will be available for successive calls within the expiry time.
Rails provides helpers such as Rails.cache.read to read the cache, Rails.cache.write to write in the cache and Rails.cache.fetch to return the results if present in the cache or else, write in the cache to return the results.
You can read more about Rails cache at
http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html Rails.cache.clear() – Flushing all the keys from memcached. Rails.cache.delete(‘posts’) – If you wish to flush any specific key from memcached server.
http://www.railscarma.com/blog/technical-articles/rails-caching-dalli-gem/
Code Refactoring Gem – Flay
Flay examines code for structural likenesses. Differences in literal values, variable, class, method names, whitespace, programming style, braces vs do/end, props versus do/end, and so forth are all overlooked,making this absolutely rad. It’s fit for recognizing both correct and close matches, and does in certainty discover a few spots in Active Record where patterns repeat. In its current state, Flay’s output is very primitive: a list of repeated code nodes, together with a weight to rank them by and line numbers and file names where the repeated code appears. Code that flay reports as comparative is a decent possibility tool for refactoring.
Command to install
sudo gem install flay
Command to see output
Cd “Path to your project folder” flay “path of the folder” Eg : flay ./app/controllers - Identifies the code duplication in all the controllers. flay ./app - Identifies the code duplication in entire project flay ./app/controllers/example_controler.rb - Identifies the code duplication in specified controller.
Example of Output An output is generated of the code duplicated areas like this:
sridevi@carmatec-MS-7788$ flay ./app/models/*.rb Total score (lower is better) = 1666 1) Similar code found in :call (mass = 170) ./app/models/example.rb:8 ./app/models/example.rb:9 ./app/models/example.rb:10 ./app/models/example.rb:11 ./app/models/example.rb:15 ./app/models/example.rb:17 ./app/models/example.rb:19 ./app/models/example.rb:20 ./app/models/example.rb:22 ./app/models/example.rb:23 2) Similar code found in :defs (mass = 154) ./app/models/example.rb:260 ./app/models/result.rb:195 3) Similar code found in :defs (mass = 138) ./app/models/feedback.rb:62 ./app/models/example.rb:54 ./app/models/result.rb:51 4) Similar code found in :call (mass = 136) ./app/models/example.rb:12 ./app/models/example.rb:13 ./app/models/example.rb:14 ./app/models/example.rb:16 ./app/models/example.rb:18 ./app/models/example.rb:21 ./app/models/example.rb:24 ./app/models/example.rb:25 5) IDENTICAL code found in :defn (mass*2 = 128) ./app/models/result.rb:7 ./app/models/summary_report.rb:7 6) IDENTICAL code found in :defn (mass*2 = 120) ./app/models/example.rb:17 ./app/models/example.rb:23
The total app score of 1666 (‘lower is better’ advice holds true) can be viewed in its individual components showing areas that provide the most bang for the buck. For experienced developers operating on their own or in a small team Flay may be unnecessary. However, on larger projects (as the one I ran it on) or those with beginner or intermediate programmers it can help increase the maintainability of your codebase. http://www.railscarma.com/blog/technical-articles/code-refactoring-gem-flay/
Ruby Developers
How to create a Ruby Gem Ruby Gems or “gem” is a package manager for the Ruby programming language that provides a standard format for distributing Ruby programs and libraries. It is easy to manage and install to your system and it can be used by various rails applications development.
Every RoR developer might have customised a gem at least once in his career, but not each one of them has actually, created a gem. Here, I am going to give a basic idea about how to create a new gem and how to publish it.
Kick off Before starting please make sure that you are using the latest ruby version. RVM is really useful in this case;
How to name your Gem Don’t blindly give a random name to your gem. Please take care of the following; Every dash represents a structure (folder, module) immersion Every underscore represents a joining in the class name
Some examples:
gem new_test_gem require ‘new_test_gem’ module/class NewTestGem
gem gem-structure-new_test_gem require ‘gem/structure/new_test_gem module/class Gem::Structure::NewTestGem
How to create your Gem To create a gem; $ bundle gem new_test_gem It will create some basic files and directories.
Where to add your code or job Your beautiful code goes here
# lib/new_test_gem.rb
Once you have added your code into the lib file then you will have to update the gemspec file;
# new_test_gem.gemspec
For Complete details go through this link => http://www.railscarma.com/blog/technical-articles/how-to-create-a-ruby-gem/
Examples corrected
I have documented this method clearly with corrections to the examples shown in this page on my blog: http://www.rubyplus.net/2016/11/aliasmethod-in-ruby.html
How to use Acts_As_Votable Gem
Acts_As_Votable is ruby gem specifically written for Rails/ActiveRecord models and This gem allows any model to be voted on upvote/downvote like/dislike, etc. It allows any model to be voted under arbitrary scopes using this gem we can vote any model. votes do not have to come from a user, they can come from any model (such as a Group or Team) and it provide an easy to write/read syntax.
Gem Installation
gem ‘acts_as_votable’
Add above line in Gemfile and run bundle install
Supported ruby and rails versions
Ruby 1.8.7, 1.9.2, 1.9.3, 2.0.0, 2.1.0 Rails 3.0, 3.1, 3.2, 4.0, 4.1+
This Gem uses vote table to save all voting information. To generate vote migration run below commands
rails generate acts_as_votable:migration rake db:migrate
To rate any model just use “acts_as_votable” in model
Example:
class Article < ActiveRecord::Base acts_as_votable end @article = Article.new(:name => ‘my new article’) @article.save @article.liked_by @user @article.votes_for.size # => 1
Read More From Here http://goo.gl/emtP8K
Scheduling Recurring Events with Ice Cube Gem
Ice_cube is a ruby library for effectively taking care of repeated events (schedules). The force lies in the ability to indicate multiple rules, and have ice_cube rapidly make sense of whether the schedule falls on a specific date (.occurs_on?), or what times it happens at (.occurrences, .first, .all_occurrences).
How to get ice cube
For install use the below syntax
gem install
if you want to get the code
gem clone git://github.com/seejohnrun/ice_cube
For creating icecube schedule
schedule = IceCube::Schedule.new if we want to speciy startdate and enddate we have option to specify in the above mentioned schedule schedule = IceCube::Schedule.new(start = Time.now, :end_time => start + 600)
Daily schedules
After creating schedule we have an option to add recurrence rule for the above mentioned schedule
consider “schedule every day” on above mentioned time
schedule.add_recurrence_rule IceCube::Rule.daily
consider the same schedule with repeat “n” number of days
schedule.add_recurrence_rule IceCube::Rule.daily(repeat_every_n_days)
in place of repeat_every_n_days you have option to specify the number of days For Weekly Monthly & Hourly You can Read It From Here http://goo.gl/XGmXp1
Volt Framework for Ruby
Volt – a new Framework for Ruby where both the server and client sides are written in Ruby via OPAL (a ruby to JavaScript compiler) so developer can write dynamic applications without writing a single JavaScript code. Volt is similar to Meteor but it doesn’t have all the portions of Meteor.
The Basic Setup for Volt Framework
Let us install Volt and create an empty app. Make sure that you have ruby (>2.1.0) and ruby gems installed.
gem install volt
We can create a new project using the volt gem:
volt new sample_project
Fire up the web server:
bundle exec volt server
We can access the Volt console with:
bundle exec volt console
The Opal Compiler
Volt applications run Ruby on both frontend and backend. So the puts statement in a controller action appears in browser window and not in terminal console. And also writing Ruby code for the front end with Volt is very easy. The opal compiler translates Ruby to JavaScript. Amazing thing about it is that there is no compilation process to follow and no build tools to install. When you run volt server, everything takes place in the background. No refresh or restart is needed when you do changes to code and data.
Calling a JavaScript alert with Ruby
# Calling JavaScript functions in Ruby module Main class MainController < Volt::ModelController # Called from front end when “todos” route loads. def todos alert ‘totes amaze’ end end end
Easy Syncing via Reactive Models
Concentrate more on this part when learning volt. Volt::Model acts as hash-like Ruby objects that sync between the front end and back end simultaneously. Usually, updates to the model happens automatically. The concept of “stores” in Volt is used to sync application data in persistent and non-persistent forms. And also a uniform means of syncing data between local storage, MangoDB, cookies, sessions and URL params.
Let’s check how to create real-time chat app of Ruby and HTML:
# Create a persistent data model. This gets stored in MongoDB. class ChatMessage < Volt::Model end
View Code:
<:Body> <form e-submit=”say”> <input class=”form-control” type=”text” value=”{{ page._input }}” /> </form> <ul> {{ _chat_messages.each do |msg| }} <ul> <button e-click=”msg.destroy”>X</button> {{ msg._text }} </ul> {{ end }} </ul>
Full HTTP Endpoint Support
Volt is not only for real-time framework. It also provides workflows for traditional HTTP application development. Checkout an example from GitHub :
# Routes for HTTP endpoint get ‘/simple_http’, controller: ‘simple_http’, action: ‘index’ get ‘/simple_http/store’, controller: ‘simple_http’, action: ‘show’ post ‘/simple_http/upload’, controller: ‘simple_http’, action: ‘upload’ # Example controller class SimpleHttpController < Volt::HttpController def index render text: ‘this is just some text’ end def show render text: “You had me at “\ “#{store._simple_http_tests.first._name}” end def upload uploaded = params[:file][:tempfile] File.open(‘tmp/uploaded_file’, ‘wb’) do |f| f.write(uploaded.read) end render text: ‘Thanks for uploading’ end end
How to Add Functionality to Ruby Classes with Decorators
Decorators allow us to add behavior to objects in runtime and don’t affect other objects of the class. Decorators can be applied when you need to dynamically add and remove responsibility to a class. The decorator pattern is a helpful alternative to creating sub-classes. They give additional functionality to a class while still keeping the public API consistent. Let’s look at an example to understand the importance of Ruby Decorators.
consider we have a Tattoo class with a price method that returns 300.
Class Tattoo def price 300 end end
Now we will add an extra color as a feature, and the price would be increased by 150
The simplest way is to create a TattooWithColour subclass that returns 450 in the price method.
class TattooWithColour < Tattoo def price 450 end end
Next, we need to represent a big tattoo that adds 200 to the price of our tattoos. We can represent this using a BigTattoo subclass of Tattoo.
class BigTattoo < Tattoo def price 500 end end
We could also have bigger sized tattoos and they may add further price to our BigTattoo. If we were to consider that these tattoos types could be used with colours, we would need to add BigTattooWithColour and BiggerTattooWithColour subclasses.
With this method, we end up with total of 6 classes. Even Double that the number if you want to represent these combinations with extra designs on tattoo. Inheriting dynamically with modules
To simplify our code, we may use modules to dynamically add behavior to our Tattoo class. Let’s write ColourTattoo and BigTattoo modules for this.
module ColourTattoo def price super + 150 end end module BigTattoo def price super + 200 end end
Now we can extend our tattoo objects dynamically using the Object#extend method.
tattoo = Tattoo.new tattoo.extend(ColourTattoo) tattoo.extend(BigTattoo)
This is good improvement over our inheritance based implementation. Instead of having sub classes, we just have one class and 3 modules. If we needed to add extra design to the equation, we need just four modules instead of 12 classes. Applying the decorator pattern
This module based solution has simplified our code greatly, but we can still improve it by using the decorator. We will consider a BiggerTatto as being formed by twice adding 150 to the cost of a Tattoo.
We can’t do this by our module based approach. It would be tempting to call tattoo.extend(BigTattoo) twice to get BiggerTattoo. Extending module second time has no effect when we have already used extend ones.
If we were to continue using the same implementation, we would need to have a BiggerTattoo module that returns super + 300 as the cost. Instead, we can use decorator that can be composed to build complex objects. We start with a decorator called BigTattoo that is a wrapper around a Tattoo object.
class BigTatto def initialize(tattoo) @tattoo = tattoo end def price @tattoo.price + 150 end end
Bigger Tattoo can now be created by using this wrapper twice on a Tattoo object.
tattoo = Tattoo.new big_tattoo= BigTattoo.new(tattoo) bigger_tattoo = BigTattoo.new(big_tattoo)
We can similarly represent colour tattoo using a TattooWithColour decorator. Using just three classes, we are now able to represent 6 types of tattoo.
Read More From Here http://www.railscarma.com/blog/technical-articles/step-step-guide-building-first-ruby-gem/
Step-By-Step Guide to Building Your First Ruby Gem
Nowadays all the functionalities in Rails are built as Ruby gems. For example we can use devise gem for the authentication part of the application. It’s like a package or library that is written in Ruby programming language. Moreover it can be imported and used by others in their programs.
Step 1 Bundler is like a dependency management tool for Ruby, which is also used by Rails. We will use Bundler for the basic gem structure. It helps us to install the correct versions of the gem and forces us to use the same in the application. So the command for that is, gem bundler install After bundling, we should specify the gem “name” that we are going to create i.e. Bundle gem “testgem” will create a repository shown below
So in this we can see the basic gem structure. Under the lib folder, version file will be used to mention the version of the Gem. We can edit the version as per our convenience and release it that will be the version in Rubygems.
Step 2 We will consider testgem.gemspec, with testgem as the name of the gem that we will create for sample. It will be used to set up the gem on rubgems, for e.g., name of the gem, summary, description, files that are required in this project, test files that are used to testing the files in the project etc.
Rake file: – This makes releasing the new versions of the gem, and also helps other developers to check the test cases if they are going to modify the particular gem. After the rake, we should create a test folder and test cases for each segments will be included here in the app directory.
Step 3 Planning to make a rubygem, then we need to analyse the requirements what to build up and what all functionalities should be included in that. While generating, we should create a sample.rb file inside lib folder and create own class with namespace because the other plugin has also the same classes then it will get conflict in the names. And require the sample.rb file in the testgem.rb file like reqiure “testgem/sample”.
Step 4 We have require “bundler/gem_tasks” in rake file so when we run rake release, it will release the gem to ruby gems and make it available. Push to git repository
Why module_function creates a private method, when including the module?
What’s the intention for doing that?
group on hash
‘
def group_by_hash hash, value hash.group_by do |k,v| v > value ? "Big" : "Small" end end marks = {"Chair" => 30, "Table" => 40, "Bed" => 60, "stool" => 20} group_by_hash(marks, 30)
Fetch with default value
You can specify default value as a fail-back if a hash doesn’t have a given key.
{a: false}.fetch(:b, true) => true {a: false}.fetch(:a, true) => false
It is useful especially in the case where you want to set default value for a method.
def initialize(args) @foo = args.fetch(:foo, 1) @bar = args.fetch(:bar, 2) # This can take over the following way. # `@bar = args[:bar] || 2` # => @bar is overwritten if caller specifies nil for :bar! end
Errno::EEXIST
When Errno::EEXIST is raised, it indicates there are permission issues, rather than an existing item.
Also implemented by other classes
It’s worth noting that this method is also implemented by other classes like Proc, Range and even String.
Most of these are missing proper examples, but you can find some useful examples here:
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).
http://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-find
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/
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.
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
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.
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 self.reverse end end
Output
irb(main):033:0> string.new_method => "gnirtS"