I know, again, I am taking a lot for granted, but in Python I was able
to do this sort of thing… And of course in Java…
Ruby is not statically typed, so there is no such thing as casting.
Just assume that string.theMethod() returns an appropriate object for
the rest of the logic to consume. As long as the returned object
responds to the appropriate methods, there will be no problems with
types.
If that doesn’t help, can you describe your goal in a broader sense?
Yeah maybe the string confused things. I don’t want to even convert to
string.
The value in string is the “human name” of the class i want to convert
it to.
So i’m converting a string into an object of class type of the string
value.
So convert “Dave” into an object of type Dave()
So, you want to do something like:
name_of_my_class.gets
name_of_my_class.to_class # Create a class out of the user input
Correct?
And I assume a case or if statement doesn’t cover all the situations
you want to do that in, also correct?
–
Phillip G.
Though the folk I have met,
(Ah, how soon!) they forget
When I’ve moved on to some other place,
There may be one or two,
When I’ve played and passed through,
Who’ll remember my song or my face.
irb(main):001:0> class A
irb(main):002:1> attr_accessor :a
irb(main):003:1> def initialize(s)
irb(main):004:2> @a = s
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):007:0> class B
irb(main):008:1> attr_accessor :b
irb(main):009:1> def initialize(s)
irb(main):010:2> @b = s
irb(main):011:2> end
irb(main):012:1> end
=> nil
irb(main):013:0> x = “B”
=> “B”
irb(main):014:0> def test(x)
irb(main):015:1> if x == “B”
irb(main):016:2> B.new(x)
irb(main):017:2> else
irb(main):018:2* A.new(x)
irb(main):019:2> end
irb(main):020:1> end
=> nil
irb(main):021:0> x = test(x)
=> #<B:0xee0bd8 @b=“B”>
irb(main):022:0> x
=> #<B:0xee0bd8 @b=“B”>
irb(main):023:0>
name_of_my_class.to_class # Create a class out of the user input
That sounds more like it.
David, you could do
class_name = … # fetch the name from somewhere
dave = Object.const_get(class_name).new
Or for a more robust solution which can also handle strings like
“Module::Class” have a look at the String#constantize method from
activesupport (part of Rails)
On Fri, Dec 3, 2010 at 11:01 AM, Rick DeNatale [email protected]wrote:
dave = Object.const_get(class_name).new
Or for a more robust solution which can also handle strings like
“Module::Class” have a look at the String#constantize method from
activesupport (part of Rails)
Here is a link
If you wish to use it, you can copy it and any other methods it depends
on,
or you can use the gem itself:
Is my “class_name” formatted correctly?
Object.const_get doesn’t parse composite names like “FireWatir::Link”.
You would have to handle that in two steps:
dave = Object.const_get(‘FireWatir’).const_get(‘Link’).new
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.