Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pluralize a symbol in Ruby (on Rails)?

This works, but looks a little bit ugly:

s = :shop
s.to_s.pluralize.to_sym   # => :shops

Is there a nicer way to pluralize a Symbol ?

like image 710
Misha Moroshko Avatar asked Dec 12 '10 23:12

Misha Moroshko


People also ask

How are symbols used in Ruby?

Symbols are objects that can be passed around like any other Ruby object. They can also be used to pass values to methods, such as in getter and setter methods in class definitions: These are just a few examples of when to use symbols in Ruby.

What is the at symbol in Ruby?

In Ruby, the at-sign ( @ ) before a variable name (e.g. @variable_name ) is used to create a class instance variable.

Why do we use symbol in Ruby?

Symbol is the most basic Ruby object we can create. It's just a name and an internal ID. Since a given symbol name refers to the same object throughout a Ruby program, Symbols are useful and more efficient than strings.


2 Answers

You can pluralize a String, which represents actual text. Symbols are a bit more abstract.

So, by definition, no. However, perhaps you could open up the Symbol class definition and add:

class Symbol
  def pluralize
    to_s.pluralize.to_sym
  end
end

Then, you can just call:

:shop.pluralize # => :shops
like image 79
Matheus Moreira Avatar answered Sep 18 '22 00:09

Matheus Moreira


Nope, that's the way.

like image 31
Ryan Bigg Avatar answered Sep 21 '22 00:09

Ryan Bigg