It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
So I want to be able to define a class like this:
class MyHouse < Home
things :bed, :lamp, :chair
end
Where Home takes care of putting those "things" in an array, like this:
class Home
attr_accessor :things
def things(*things)
#things = []
things.each { |thing| #things << thing }
end
end
The problem with this is I get:
NoMethodError: undefined method `things' for MyHouse:Class
I know there's a way to do this. Help appreciated,
Thanks,
Pachun
def things should be def self.things
That makes it a class method rather than an instance method.
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Given this Hash:
myXML = {:_id=>BSON::ObjectId('51ad8d83a3d24b3b9f000001'),
"Comment"=>nil,
"Line"=>
[{"LineNumber"=>"3.1",
"Item"=>"fruit-004",
"Description"=>"Peach",
"Quantity"=>"1",
"UnitCost"=>"1610",
"DeclaredValue"=>"0",
"PointValue"=>"13"},
{"LineNumber"=>"8.1",
"Item"=>"fruit-001",
"Description"=>"Fruit Set",
"Quantity"=>"1",
"UnitCost"=>"23550",
"PointValue"=>"105",
"PickLine"=>
[{"PickLineNumber"=>"8.1..1",
"PickItem"=>"fruit-002",
"PickDescription"=>"Apple",
"PickQuantity"=>"1"},
{"PickLineNumber"=>"8.1..2",
"PickItem"=>"fruit-003",
"PickDescription"=>"Orange",
"PickQuantity"=>"2"}]}],
"MemberId"=>"A00000001",
"MemberName"=>"Bruce",
"DeliveryId"=>"6377935",
"ShipToAddress1"=>"123-4567",
"OrderDate"=>"05/08/13",
"Payments"=>
[{"PayType"=>"Credit Card", "Amount"=>"1000"},
{"PayType"=>"Points", "Amount"=>"5390"}]}
I'm able to remove the key/value pair with "Comment" key that has nil value with the code:
myXML.each do |key, value|
myXML.delete(key) if myXML[key] == nil
end
I believe there's a much better way to do this with less code in Ruby.
Does the following code work as you expect?
myXML.delete_if{|key, value| value.nil?}
This is not appropriate of course if you intend to delete recursively.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Does polymorphism exist in Ruby? I've read that Ruby does not support polymorphism, and instead it supports method overloading and method overriding. Can someone clarify this for me with an example?
Yes, Ruby does support polymorphism.
Consider the case of simple class inheritance where an instance of a derived class "is a" instance of both the child and parent classes:
class Parent; end
class Child < Parent; end
o = Child.new
o.is_a?(Child) # => true
o.is_a?(Parent) # => true
Note that this example is also valid for included modules:
a = Array.new
a.is_a?(Array) # => true
a.is_a?(Enumerable) # => true
Of course, Ruby also encourages duck typing, which may be the source of confusion regarding the question of properly supporting polymorphism.
Ruby is a highly polymorfic language, in the sense methods don't automatically infer what data type you are passing to them, as long as the object behaves like expected. Example:
def concat(a,b)
a.to_s + b.to_s
end
concat('a', 'bcd') #=> "abcd"
concat(5, 10) #=> "510"
concat([1,2,3], ' is an Array') #=> "[1, 2, 3] is an Array"
As long as a and b respond to to_s, the function will output as expected. Check more about Duck Typing for examples.
Ruby doesn't support method overloading. The very idea of method overloading doesn't even make sense in a dynamically typed language.
Ruby does support ad-hoc polymorphism, just like pretty much every object-oriented language on the planet.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I would like to write a simple documentation generator in ruby that will take a standard .rb file and list all of the classes or modules defined, all of the methods and variables defined in each class or module, and indicate whether any methods are aliased or inherited from a super class.
How should I approach this?
Reverse-engineering YARD is probably the best idea (not sure why it's a comment). Alternatively, you could probably do this with the ruby_parser gem.
require 'ruby_parser'
class SillyRubyParserExample
def self.example
class_eval(RubyParser.new.parse(<<-EOS
class ParseMe
def a() end
def b() end
end
EOS
).inspect)
end
def self.s(*args)
if args[0] == :defn
puts "def " + args[1].to_s
elsif args[0] == :class
puts "class " + args[1].to_s
end
end
end
SillyRubyParserExample.example
Produces:
def a
def b
class ParseMe
Of course, this is just a silly example, merely listing methods and classes.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
How do you make a filter in ruby? I know the function already exists in rails but how do we code it in a ruby program? Here is the program:
module Filter
def before_filter *args
end
def after_filter *args
end
end
class Ingredient
def one
puts "in one"
end
def two
puts "in two"
end
def three
puts "in three"
end
def four
puts "in four"
end
extend Filter
before_filter :one, :two
after_filter :four
end
dish1 = Ingredient.new
dish1.three
Rails can get away with this because they control how the methods get invoked. But here, you're directly calling three from the outside.
To fit within the constraints you've presented, any code which does this will be utterly grotesque. Also, what does the after filter do? Does it determine the return value?
I have implemented something similar to this, though with a slightly different interface that saves it some of the grotesqueness, but still, it's terrible. https://gist.github.com/3450271
Furthermore, there's an obvious question of why you would ever need such a thing.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
Here's what I am trying to do: The user enters a string. The string contains 2 parts and will look like this:
{EventClass: someMethod=>arg1, arg2, arg3....}, {Action: someMethod=>arg1, arg2, arg3....}
A concrete example of this would be:
{TwitterEvent: newTweet=>arg1, arg2, arg3....}, {PersistenceAction: saveToHardDrive=>arg1 arg2...}
Then I will parse this string, instantiate an instance of TwitterEvent, call that method on it. Then do the same thing for PersistenceAction
What the best "design" for this type of application? How would I dynamically instantiate classes from parsed string and then call method? And potentially, the method will have arguments? How would I detect/handle errors?
Get class object from name string:
Kernel.const_get('TwitterEvent')
Invoke arbitrary method on object:
event.send(:new_tweet)
The rest is up to you. :-)
You want to use respond_to? and send . Send allows you to invoke a method using a symbol. You can use to_sym to convert a string to a symbol.
Here you go
str = "{TwitterEvent: newTweet=>arg1, arg2, arg3}, {PersistenceAction: saveToHardDrive=>arg1, arg2}"
regexp = /^{(\w+):\s*(\w+)=>([^}]+)},\s*{(\w+):\s*(\w+)=>([^}]+)}$/
regexp.match(str).to_a[1..-1].each_slice(3) do |s|
# s[0] .. class name
# s[1] .. class method
# s[2] .. method parameters as a single string
# do something similar to Sergio Tulentsev suggestion
end