Robert Klemme
8/10/2006 4:23:00 PM
On 10.08.2006 18:17, Josselin wrote:
> I know I can write it the 'ugly common way' (loop)
> but I'd like to see how it can be done the Ruby way ... (I am a newbie...)
>
> here is an array
> roles = [ "a", "b", "c", "d", "e" ]
>
> Depending upon a variable 'user.role',
> I would like to suppress all elements in the array , less or equal to
> this variable
>
> ex :
> user.role = "a" #=> roles = ["b", "c", "d", "e" ] "a" deleted
> user.role = "b" #=> roles = ["c", "d", "e" ] "a", "b" deleted
> user.role = "c" #=> roles = [ "d", "e" ] "a", "b", "c"
> deleted
> user.role = "d" #=> roles = [ "e" ] "a", "b", "c",
> "d" deleted
> user.role = "e" # do nothing
>
> thanks for your tips
>
> Joss
> (I am on my way to buy the Ruby Recipes PDF Cookbook...)
>
Do you actually want to modify the array or do you just want to work
with the reduced set? Does this help?
>> roles = %w{a b c d e f}
=> ["a", "b", "c", "d", "e", "f"]
>> roles.select {|r| r >= "c"}
=> ["c", "d", "e", "f"]
>> roles.select {|r| r > "c"}
=> ["d", "e", "f"]
>> roles
=> ["a", "b", "c", "d", "e", "f"]
>> roles.delete_if {|r| r <= "c"}
=> ["d", "e", "f"]
>> roles
=> ["d", "e", "f"]
Kind regards
robert