# How to pass arguments to a Rake task

Photo by Lukas on Unsplash

There are many ways how to pass an argument to a rake task, some of these are covered in at this blog post.

IMHO, the most elegant way to do this is using the first way described at post, the Rake Way:

  task :add, [:num1, :num2] do |_, args|
puts args[:num1].to_i + args[:num2].to_i
end


And, you run it…

  $rake add[1,2] # => 3  All right! Nothing to do here! YAY! A common task block is like this:  task some_task: :environment do # Do awesome things... end  The :environment symbol is what tells to rake task to load your entire Rails environment. So, without this you can’t access your models, for example. To using arguments in a elegant way and load your Rails environment in your Rake task, you can write your task method like this:  task :add, [:num1, :num2] => :environment do |_, args| puts args[:num1].to_i + args[:num2].to_i end  And, this is the output: $ rake add[1,2]
# => 3


Thanks! 😄