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