M
Maurizio De Santis
Hello!
suppose I want to modify Array.slice() (and consequentially, Array[]) in
order to accept a RegExp as argument, and return values matching the
regular expression. I tried to solve this problem in this way:
class Array
def slice_with_regexp(*args)
puts args
return self.select{ |val| val.to_s =~ args[0] } if args.size == 1
and args[0].is_a?(RegExp)
end
alias_method :slice_without_regexp, :slice
alias_method :slice, :slice_with_regexp
end
arr = %w[a b c]
puts arr.slice(/a/)
but executing this script I get this error:
(?-mix:a)
scripts.rb:8:in `slice_with_regexp': uninitialized constant RegExp
(NameError)
from scripts.rb:17:in `<main>'
Surely I did something wrong, but the very question is: what is the
correct way to get the desired effect (that is
arr = %w[a b c]
puts arr[/a/]
=> ["a"]
puts arr.slice(/a/)
=> ["a"]
?
suppose I want to modify Array.slice() (and consequentially, Array[]) in
order to accept a RegExp as argument, and return values matching the
regular expression. I tried to solve this problem in this way:
class Array
def slice_with_regexp(*args)
puts args
return self.select{ |val| val.to_s =~ args[0] } if args.size == 1
and args[0].is_a?(RegExp)
end
alias_method :slice_without_regexp, :slice
alias_method :slice, :slice_with_regexp
end
arr = %w[a b c]
puts arr.slice(/a/)
but executing this script I get this error:
(?-mix:a)
scripts.rb:8:in `slice_with_regexp': uninitialized constant RegExp
(NameError)
from scripts.rb:17:in `<main>'
Surely I did something wrong, but the very question is: what is the
correct way to get the desired effect (that is
arr = %w[a b c]
puts arr[/a/]
=> ["a"]
puts arr.slice(/a/)
=> ["a"]
?