Two Methods for converting strings into classes in Ruby: ruby2

Source: Internet
Author: User

Two Methods for converting strings into classes in Ruby: ruby2

Recently, there is a need to use a string as a class. For example:

There is a string "ChinaMag" that calls methods under the ChinaMag Class Based on this string.

Solution:

1. rails can use the constantize method.

Copy codeThe Code is as follows:
Pry (main)> 'chinamag'. constantize
=> ChinaMag
Pry (main)> "Test: Unit". constantize
=> Test: Unit

2. ruby can use Object. const_get ("String ").

Copy codeThe Code is as follows:
Pry (main)> Object: const_get ('chinamag ')
=> ChinaMag
 
Pry (main)> module Foo
Pry (main) * class Bar
Pry (main) * end
Pry (main) * end
=> Nil
Pry (main)> 'foo: bar'. split (':'). inject (Object) {| o, c | o. const_get c}
=> Foo: Bar


RUBY string format conversion

Well, the first step is to convert it to hexadecimal: icon = "22 12 41 2 1 8 43 211 42" # => "22 12 41 2 1 8 43 211 42" icon. split. map {| I. to_ I .to_s (16) }#=> ["16", "c", "29", "2", "1", "8", "2b ", "d3", "2a"] And then the Formatting you said (I don't know what you mean, but I don't know if I want to add 0 in front of a single digit): icon. split. map {| I. to_ I .to_s (16 )}. map {| s. size = 1? S. insert (0, "0"): s }#=> ["16", "0c", "29", "02", "01", "08 ", "2b", "d3", "2a. split. map {| I. to_ I .to_s (16 )}. map {| s. size = 1? S. insert (0, "0"): s}. join => "160c290201082bd32a"

Array conversion from ruby strings

@ Names = @ story. name. split
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.