Ruby itself

·

1 min read

It’s interesting to discover that Ruby has an instance method itself for the object. It returns the receiver itself—whatever the kind of receiver is.

Let’s see a few examples:


website = "Hashnode" # => "Hashnode"
website.itself # => "Hashnode"
website.object_id == website.itself.object_id # => true
age = 18
age.itself # => 18
age.object_id == age.itself.object_id # => true
task_completed = true
task_completed.itself # => true
task_completed.object_id == task_completed.itself.object_id # => true

This can be very useful when rendering a collection of checkboxes from a plain array rather than an array of objects in Rails.

tags = ["Ruby", "Ruby on Rails", "JavaScript", "TypeScript", "React", "React Native", "Python"]

<%= form_for @post do |f| %>
  <%= f.collection_check_boxes :tags, tags, :itself, :itself %>
  <%= f.submit %>
<% end %>

The form will contain a group of tags as checkboxes, with each checkbox's label and value referring to the corresponding tag itself.

This is it for Ruby’s instance method itself! I hope you find this post helpful in your ruby project.