It’s often a requirement in various projects to convert numbers from decimal to text representations of several other bases, such as hexadecimal or binary.
Did you know you can convert to any base from 2 to 36 in one line in Ruby?
Using the Fixnum#to_s method, you can quickly convert any Fixnum object to the textual format of another base:
255.to_s(36) #=> "73" 255.to_s(16) #=> "ff" 255.to_s(2) #=> "11111111"
This tip was submitted by Nathan Kleyn.
To add on corresponding elements of several arrays:
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
[a, b, c].transpose.map { |x| x.reduce :+ }
# => [12, 15, 18]Given a number of arrays, each contains same number of arrays with the same length. To merge corresponding arrays:
a = [ [1, 2], [3, 4] ] b = [ [5, 6], [7, 8] ] c = [ [9, 10], [11, 12] ] (a.transpose + b.transpose + c.transpose).transpose # => [[1, 2, 5, 6, 9, 10], [3, 4, 7, 8, 11, 12]]
To do the same job, but with arrays that are not necessarily equal in length:
a = [ [1], [2, 3] ]
b = [ [4, 5], [] ]
c = [ [6,7,8], [9, 10, 11, 12] ]
[a, b, c].transpose.map { |x| x.reduce :+ }
# => [[1, 4, 5, 6, 7, 8], [2, 3, 9, 10, 11, 12]]Check out the documentation on Array#transpose, Array#map and Enumerable#reduce.
This tip was submitted by Haitham Mohammad.
You can easily load SQL files like this:
rails db < path_to_sql_file.sql # Rails 3 script/dbconsole < path_to_sql_file.sql # Rails 2
You can write an Around Alias in three simple steps:
Example:
class String alias :orig_length :length def length "Length of string '#{self}' is: #{orig_length}" end end "abc".length #=> "Length of string 'abc' is: 3"
This tip was submitted by Nimesh Nikum.
When rendering JSON from your controllers (or when using to_json directly), Rails 3.1 and above won’t include the root element in the output:
post = Post.first
# => #<Post id: 1, title: "My first blogpost" ...
post.to_json
# => "{\"id\":1,\"title\":\"My first blogpost\", ...}"To include the root element (post in this example), set ActiveRecord::Base.include_root_in_json to true:
# wrap_paramters.rb if defined?(ActiveRecord) ActiveRecord::Base.include_root_in_json = true end
Result:
post.to_json
# => "{\"post\":{\"id\":1,\"title\":\"My first blogpost\", ...}}"In version of Rails < 3.1, including the root element is the default. You can disable it by adding ActiveRecord::Base.include_root_in_json = false to one of your files in config/initializers or in application.rb/environment.rb directly.
More info in the API docs on ActiveModel::Serializers::JSON.
You can set the name of the current Ruby process, the one that you would see from the ps command for example.
Simply assign a string to the global variable $PROGRAM_NAME:
$PROGRAM_NAME = 'Hello from Rubyland!'
puts 0ドル # This is an alias for the same thing.This is a great way for long running scripts or daemon processes to communicate status information to people who are looking in on them.
5.times do |i| $PROGRAM_NAME = "Ruby Quicktips Example: On iteration #{i}" sleep 5 # I'm really busy!! end
Execute something like this in your terminal:
ps x | grep Quicktips
This tip was submitted by Jesse Storimer.
This does not work:
class Foo private def self.bar end end
Foo.bar will be public.
To make it private, you can use Module#private_class_method:
class Foo def self.bar end private_class_method :bar end
…or define it differently:
class Foo class << self private def bar end end end
This tip was submitted by two-bit-fool.
This snippet simply clears your logs when they are too large. Every time you run rails server or rails console it checks log sizes and clears the logs for you if necessary.
# config/initializers/clear_logs.rb if Rails.env.development? MAX_LOG_SIZE = 2.megabytes logs = File.join(Rails.root, 'log', '*.log') if Dir[logs].any? {|log| File.size?(log).to_i > MAX_LOG_SIZE } $stdout.puts "Runing rake log:clear" `rake log:clear` end end
This tip was submitted by pahanix.
As an example, let’s say you want to create an index of ActiveRecord objects by their id. Use the Hash constructor that accepts an Array of key-value pairs and do it in one line:
posts_by_id = Hash[*Post.all.map{ |p| [p.id, p] }.flatten]This tip was submitted by http://Fullware.net/.
If you want to initialize new instances of your class and specify values for its attributes directly, you can implement an initialize method with a lot of arguments. Or you can use a Hash - the Rails way:
my_puppy = Dog.new(:name => "Luke", :birthdate => Time.now)You can do this by using a general initialize implementation:
module GeneralInit
def initialize(*h)
if h.length == 1 && h.first.kind_of?(Hash)
h.first.each { |k,v| send("#{k}=",v) }
end
end
endFor every class that needs to take advantage of this, you just have to include GeneralInit. The initialize method will be available and work the way you expect it to.
It is still possible to create a new instance without arguments (Dog.new), or passing in a Hash with attribute/value pairs (as shown in the example above).
This tip was submitted by Rik Vanmechelen.
You can use Array#join to concatenate Array elements to a String:
[1, 2, 3].join('+')
# => "1+2+3"Array#* has the same effect when you pass it a String:
[1, 2, 3] * '+'
# => "1+2+3"This tip was submitted by Ciur Eugen.
Instead of using the database-specific command to start your project’s database console, Rails provides one consistent interface for the most popular databases (MySQL, PostgreSQL and SQLite):
script/dbconsole [RAILS_ENV] # Rails 2 rails dbconsole [RAILS_ENV] # Rails 3 rails db [RAILS_ENV] # Rails 3 alias
Ever wanted to modify the keys and values of a Hash? Enumerable::inject has you covered.
Try this snippet from Stack Overflow:
my_hash = { a: 'foo', b: 'bar' }
# => {:a=>"foo", :b=>"bar"}
a_new_hash = my_hash.inject({}) { |h, (k, v)| h[k.upcase] = v.upcase; h }
# => {:A=>"FOO", :B=>"BAR"}When you set a variable in a section of code that is never executed, the variable will still be defined.
if false
a = 'whatever'
end
puts a
# => "nil"
# Does NOT raise 'NameError: undefined local variable or method `a' for main:Object'This post was submitted by Olivier El Mekki.
String#gsub is a common method for finding and replacing all occurrences of a text in a string. It is often used, like this:
"Where is the needle in the haystack?".gsub('needle', 'NEEDLE') # => "Where is the NEEDLE in the haystack?"
But gsub can also use regular expressions, like this:
"Where is the needle in the haystack?".gsub(/n\w{5,}/, '*') # => "Where is the * in the haystack?"
gsub can also take a block which can use all of the global match variables, such as $&, $', 1ドル, 2ドル, to build up a replacement string. This allows for replacement strings to be generated using information from the match, like this:
"Where is the needle in the nefarious haystack?".gsub(/n\w{5,}/) do '*' + $&.upcase + '*' end # => "Where is the *NEEDLE* in the *NEFARIOUS* haystack?"
Blocks provide gsub with the ability to generate the substitution string using information about a match that is only available after a match is identified. You can use any of the global variables associated with matches from within the block.
This tip was submitted by Tim Rand.