Casa Open

Teste suas expressões regulares na web

0 comentários

Vai uma dica de um ótimo site, o Rubular. Com ele você testa suas expressões regulares em Ruby de forma pratica e rápida e ainda pode adquirir um link de seus testes.








Project Euler #1

0 comentários
O Projeto Euler foi iniciado por Colin Hughes (aka Euler) em outubro de 2001 e consiste em diversos problemas que envolvem matemática e computação, sendo que alguns são possíveis resolver sem o uso da computação e outros não. Segundo a descrição do projeto, este teve como principal motivação oferecer uma plataforma para que mentes curiosas mergulhem em áreas desconhecidas.

Salvo as devidas explicações, irei começar a resolver alguns problemas, de preferência em Ruby, e postar as soluções aqui.

Então... vamos ao problema 1:

Descrição

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

Solução

sum = 0
(1..999).each { |x| sum += x if x%3 == 0 or x%5 == 0 }
puts sum

Resposta

233168


Doc da sua aplicação Rails

0 comentários
Já experimentou o comando rake doc:app ?

rake doc:app

Ele cria uma doc semelhante a documentação do Ruby com todos os arquivos, classes e métodos da sua sua aplicação no diretório /doc/app/ .

Bom, mas existem muitos outros comandos interessantes, para conhecê-los basta rodar:

rake -T


rake db:abort_if_pending_migrations        # Raises an error if there are pending migrations
rake db:charset                            # Retrieves the charset for the current environment's database
rake db:collation                          # Retrieves the collation for the current environment's database
rake db:create                             # Create the database defined in config/database.yml for the current RAILS_ENV
rake db:create:all                         # Create all the local databases defined in config/database.yml
rake db:drop                               # Drops the database for the current RAILS_ENV
rake db:drop:all                           # Drops all the local databases defined in config/database.yml
rake db:fixtures:identify                  # Search for a fixture given a LABEL or ID.
rake db:fixtures:load                      # Load fixtures into the current environment's database.
rake db:migrate                            # Migrate the database through scripts in db/migrate and update db/schema.rb ...
rake db:migrate:down                       # Runs the "down" for a given migration VERSION.
rake db:migrate:redo                       # Rollbacks the database one migration and re migrate up.
rake db:migrate:reset                      # Resets your database using your migrations for the current environment
rake db:migrate:up                         # Runs the "up" for a given migration VERSION.
rake db:reset                              # Drops and recreates the database from db/schema.rb for the current environm...
rake db:rollback                           # Rolls the schema back to the previous version.
rake db:schema:dump                        # Create a db/schema.rb file that can be portably used against any DB support...
rake db:schema:load                        # Load a schema.rb file into the database
rake db:seed                               # Load the seed data from db/seeds.rb
rake db:sessions:clear                     # Clear the sessions table
rake db:sessions:create                    # Creates a sessions migration for use with ActiveRecord::SessionStore
rake db:setup                              # Create the database, load the schema, and initialize with the seed data
rake db:structure:dump                     # Dump the database structure to a SQL file
rake db:test:clone                         # Recreate the test database from the current environment's database schema
rake db:test:clone_structure               # Recreate the test databases from the development structure
rake db:test:load                          # Recreate the test database from the current schema.rb
rake db:test:prepare                       # Check for pending migrations and load the test schema
rake db:test:purge                         # Empty the test database
rake db:version                            # Retrieves the current schema version number
rake doc:app                               # Build the RDOC HTML Files
rake doc:clobber_app                       # Remove rdoc products
rake doc:clobber_plugins                   # Remove plugin documentation
rake doc:clobber_rails                     # Remove rdoc products
rake doc:guides                            # Generate Rails guides
rake doc:plugins                           # Generate documentation for all installed plugins
rake doc:plugins:brazilian-rails           # Generate documentation for the brazilian-rails plugin
rake doc:plugins:human_attribute_override  # Generate documentation for the human_attribute_override plugin
rake doc:plugins:jrails                    # Generate documentation for the jrails plugin
rake doc:plugins:paperclip                 # Generate documentation for the paperclip plugin
rake doc:plugins:will_paginate             # Generate documentation for the will_paginate plugin
rake doc:rails                             # Build the RDOC HTML Files
rake doc:reapp                             # Force a rebuild of the RDOC files
rake doc:rerails                           # Force a rebuild of the RDOC files
rake gems                                  # List the gems that this rails application depends on
rake gems:build                            # Build any native extensions for unpacked gems
rake gems:build:force                      # Force the build of all gems
rake gems:install                          # Installs all required gems.
rake gems:refresh_specs                    # Regenerate gem specifications in correct format.
rake gems:unpack                           # Unpacks all required gems into vendor/gems.
rake gems:unpack:dependencies              # Unpacks all required gems and their dependencies into vendor/gems.
rake jrails:install:javascripts            # Installs the jQuery and jRails javascripts to public/javascripts
rake jrails:update:javascripts             # Copies the jQuery and jRails javascripts to public/javascripts
rake log:clear                             # Truncates all *.log files in log/ to zero bytes
rake middleware                            # Prints out your Rack middleware stack
rake notes                                 # Enumerate all annotations
rake notes:custom                          # Enumerate a custom annotation, specify with ANNOTATION=WTFHAX
rake notes:fixme                           # Enumerate all FIXME annotations
rake notes:optimize                        # Enumerate all OPTIMIZE annotations
rake notes:todo                            # Enumerate all TODO annotations
rake paperclip:clean                       # Cleans out invalid attachments.
rake paperclip:refresh                     # Refreshes both metadata and thumbnails.
rake paperclip:refresh:metadata            # Regenerates content_type/size metadata for a given CLASS (and optional ATTA...
rake paperclip:refresh:thumbnails          # Regenerates thumbnails for a given CLASS (and optional ATTACHMENT).
rake rails:freeze:edge                     # Lock to latest Edge Rails, for a specific release use RELEASE=1.2.0
rake rails:freeze:gems                     # Lock this application to the current gems (by unpacking them into vendor/ra...
rake rails:template                        # Applies the template supplied by LOCATION=/path/to/template
rake rails:unfreeze                        # Unlock this application from freeze of gems or edge and return to a fluid u...
rake rails:update                          # Update both configs, scripts and public/javascripts from Rails
rake rails:update:application_controller   # Rename application.rb to application_controller.rb
rake rails:update:configs                  # Update config/boot.rb from your current rails install
rake rails:update:generate_dispatchers     # Generate dispatcher files in RAILS_ROOT/public
rake rails:update:javascripts              # Update your javascripts from your current rails install
rake rails:update:scripts                  # Add new scripts to the application script/ directory
rake routes                                # Print out all defined routes in match order, with names.
rake secret                                # Generate a crytographically secure secret key.
rake stats                                 # Report code statistics (KLOCs, etc) from the application
rake test                                  # Run all unit, functional and integration tests
rake test:benchmark                        # Run tests for benchmarkdb:test:prepare / Benchmark the performance tests
rake test:functionals                      # Run tests for functionalsdb:test:prepare / Run the functional tests in test...
rake test:integration                      # Run tests for integrationdb:test:prepare / Run the integration tests in tes...
rake test:plugins                          # Run tests for pluginsenvironment / Run the plugin tests in vendor/plugins/*...
rake test:profile                          # Run tests for profiledb:test:prepare / Profile the performance tests
rake test:recent                           # Run tests for recentdb:test:prepare / Test recent changes
rake test:uncommitted                      # Run tests for uncommitteddb:test:prepare / Test changes since last checkin ...
rake test:units                            # Run tests for unitsdb:test:prepare / Run the unit tests in test/unit
rake time:zones:all                        # Displays names of all time zones recognized by the Rails TimeZone class, gr...
rake time:zones:local                      # Displays names of time zones recognized by the Rails TimeZone class with th...
rake time:zones:us                         # Displays names of US time zones recognized by the Rails TimeZone class, gro...
rake tmp:cache:clear                       # Clears all files and directories in tmp/cache
rake tmp:clear                             # Clear session, cache, and socket files from tmp/
rake tmp:create                            # Creates tmp directories for sessions, cache, sockets, and pids
rake tmp:pids:clear                        # Clears all files in tmp/pids
rake tmp:sessions:clear                    # Clears all files in tmp/sessions
rake tmp:sockets:clear                     # Clears all files in tmp/sockets



Em qual ambiente estamos?

0 comentários
Já teve a necessidade de saber em qual ambiente de trabalho - production, development, test e etc - você está? Acredito que sim! Logo segue algumas dicas para saber isso:

if Rails.env == 'development'
  puts 'Estamos no development'
elsif Rails.env == 'production'
  puts 'Estamos no production'
end

Ou:

puts 'Estamos no development' if Rails.env.development? 
puts 'Estamos no production' if Rails.env.production? 
puts  'Estamos no test' if Rails.env.test?  
puts  'Estamos no whatever' if Rails.env.whatever?

Ou usando a variável de ambientes RAILS_ENV:

if RAILS_ENV == 'development'
  puts 'Estamos no development'
elsif RAILS_ENV == 'production'
  puts 'Estamos no production'
end


Wallpaper Ruby on Rails

0 comentários
Estava procurando um papel de parede novo e olhe o que encontrei:
[ P.S. basta clicar nas fotos para ser redirecionado aos devidos sites ]

















Interpretador Ruby Online

0 comentários
Já passou pela experiência de querer executar algum algoritmo mas estava sem o devido interpretador ou compilador? Certamente sim! Mas nessas horas o site CodePad é uma ótima saída, com ele você pode interpretar/compilar código fonte de várias linguagens tais com: Ruby, PHP, C, C++, Haskell, Lua, Ocaml, Perl e outras. Além disso, ele disponibiliza o seu código juntamente com a respectiva saída através de uma url curta de forma semelhante as usadas no Twitter.
Sem dúvida esses fatores apontam o CodPad como uma boa maneira para mostrar,  de forma rápida,  um código simples para alguém.

Interessou? Então entre no site e/ou veja como é o seu funcionamento.

P.S. Fiz alguns testes em Ruby e em todos tive sucesso, veja um deles http://codepad.org/QrVXq8oj.


Precedência em operadores lógicos

2 comentários
Antes de qualquer coisa, veja os seguintes códigos e seus respectivos retornos:

true and false #=> false
true && false #=> false
true or false #=> true
true || false #=> true

Em vista disso, logo vem a pergunta: Qual a diferença entre "and" e "&&" e entre "or" e "||"?
A resposta é simples, "&&" e "||" possuem maior precedência que "and" e "or". Sendo que o "&&" possui maior precedência que o "||" e o "and" possui a mesma precedência que "or". Veja alguns exemplos:

true or false and false #=> false

Neste caso o código é resolvido da esquerda para a direita, ou seja: primeiro o "or" e em seguida o "and".

true or false && false #=> true

Como o "&&" possui maior precedência ele é resolvido primeiramente e depois o "or".


© 2010 Casa Open. Powered by Blogger