[] Ruby String method

When I read the Beast source code, I found a lot of code like this:

<%= 'Password'[:password_title] %> 

It looks like calling the [] method with a character as an input parameter to a string for me, but I did not find this type of parameter to the String [] method in the ruby ​​API. What does it mean? thanks in advance.

+6
string ruby ruby-on-rails monkeypatching
source share
3 answers

This method, added by the "Gibberish" Beast plugin, is used for internationalization. Remember that classes are open in Ruby, so you cannot always rely on a standard API in such cases!

+11
source share

In the beast’s source, check the mascot plugin, which changes the String class to accept characters in brackets.

The String class itself does nothing sensible by using the str[symbol] method.

+4
source share
 str[fixnum] => fixnum or nil str[fixnum, fixnum] => new_str or nil str[range] => new_str or nil str[regexp] => new_str or nil str[regexp, fixnum] => new_str or nil str[other_str] => new_str or nil 

Here is what I found. If the character here is String, I still don't understand the meaning of the code. Why not just use:

 <%= 'password' %> 

or even:

 password 
+1
source share

All Articles