Question

How can one generate a new list has all the elements of old-list except for some parts bracketted between line where f1(start_line) is true and f2(end_line) is true

Naive code

def remove_bracketted(orig_list)
    ignore_flag = false
    new_list = []

    orig_list.each do |v|
        if f1(v)
            ignore_flag = true
        elsif f2(v)
            ignore_flag = false
        else 
            new_list << v unless ignore_flag
        end
    end
end

For instance, with the following definitions of f1 and f2

def f1(v)
    v == "{"
end

def f2(v)
    v == "}"
end

when run on

foo(a,b)
{
    s1
    s2
    s3
}
bar(a,b)
{
    t1
    t2
    t3
}

Some other text

one should get

foo(a,b)
bar(a,b)
Some other text

Kindly note that f1 and f2 can be any function of type a -> Bool where list elements are all of type a and not just comparison to an open brace and close brace.

Edit: I was looking for a solution like this which works if there is only one such pair

new_list = old_list.take_while(not(condition1)).concat(old_list.drop_while(not(condition2)))
Was it helpful?

Solution

This might be a place where the flip-flop operator would be useful:

def val1; '{' end
def val2; '}' end

p ['a','b','{','a','}','f','d','d'].reject{|x| true if (val1==x)..(val2==x)}
#=> ["a", "b", "f", "d", "d"]
p ['a','b','{','a','}','f','d','d'].select{|x| true if (val1==x)..(val2==x)}
#=> ["{", "a", "}"]

OTHER TIPS

ScriptDevil, i guess some people won't like your way of making a question so i suggest asking it somewhat politer and not offer us a 'task' like we are in class. We are here to help and you should show us what you tried yourself.

Here is a way of doing what you want.

class String
  def replace_between start, ending, replace_with
    gsub(/#{start}[^#{ending}]*#{ending}/m, replace_with)
  end
end    
txt = %[
foo(a,b)
{
    s1
    s2
    s3
}
bar(a,b)
{
    t1
    t2
    t3
}
Some other text
]

puts txt.replace_between '{', '}', ''

# oo(a,b)

# bar(a,b)

# Some other text
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top