From: Josselin Date: 2006-08-11T15:50:05+09:00 Subject: Re: good writing in Ruby... On 2006-08-10 18:25:19 +0200, Philip Hallstrom said: >> 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 > > Maybe... > > roles = roles.map {|x| x <= user.role ? x : nil }.compact > > haven't tested it though... I'll test it, values in array are strings : 'god', 'administrator', ''manager', 'owner', 'customer' exclusion is based on a prority order if current_user role is 'god' then exclude 'god' (there can be only one god) if current_user role is 'administrator' then exclude 'god' and 'administrator' if current_user role is 'manager' then exclude 'god' and 'administrator' and 'manager' if current_user role is 'owner' then exclude 'god' and 'administrator' and 'manager' and 'owner' ... as roles could change in the future (and also ro avoid possible localization issues) I believe it would be better to work with an additional integer priority field in the 'role' table, so I can sort the collection on priority and get a sorted roles array whatever is in the table... thanks