I came across the following script from "Why's poignant guide to Ruby".
http://pastie.org/1034445
And, I have included my questions as comments in the script.
Please let me know what you think.
def wipe_mutterings_from( sentence )
unless sentence.respond_to? :include? # What is meant by this statement?
raise ArgumentError, "cannot wipe mutterings from a #{ sentence.class }"
end
This statement is calling the respond_to? method of the object refered
by the variable sentence:
http://ruby-doc.org/core/classes/Object.html#M000331
If the method returns true, it means that the object can be sent the
message :include?, that you can call the method #include? of that
object. For example:
irb(main):010:0> [].respond_to? :include?
=> true
irb(main):011:0> "test".respond_to? :include?
=> true
irb(main):012:0> class A
irb(main):013:1> end
=> nil
irb(main):014:0> a = A.new
=> #<A:0xb73f5f2c>
irb(main):015:0> a.respond_to? :include?
=> false
irb(main):016:0> class B
irb(main):017:1> def include?
irb(main):018:2> "test"
irb(main):019:2> end
irb(main):020:1> end
=> nil
irb(main):021:0> b = B.new
=> #<B:0xb73e71fc>
irb(main):022:0> b.respond_to? :include?
=> true
while sentence.include? '('
open = sentence.index( '(' )
close = sentence.index) ')', open) # Why the "open" here?
Check the #index method of String (possibly sentence is a String,
cause the code is checking for substrings):
http://ruby-doc.org/core/classes/String.html#M000784
If you pass a second argument, the search for the substring is started
at that offset from the beginning. In the above snippet, it's checking
for the first ')' after a '('.
sentence[open..close] = '' if close # How is this sentence read?
And, is [open..close] and array AND range?
Check the #[]= method of String:
http://ruby-doc.org/core/classes/String.html#M000772
When passed a range, it's referring to the characters that start and
end at the first and last value of the range, and will substitute the
left hand side (an empty string) for the characters between those
offsets. Basically it's saying: take the substring starting at the
offset "open" and ending at the offset "close" and remove it (sub by
an empty string).
end
end
Hope this helps,
Jesus.