Can i shorten up this function?

hey there, i have a function that checks to see if a string is in a
comma separated list

it looks like this
def get_in_list(status)
my_list = ‘x,j,m,jrn,fnk,foo,other’
my_list_array = my_list.split(’,’)
if my_list_array.include?(status)
return true
else
return false
end
end

i dunno, just thought there might be a prettier way to do this.
any suggestions ?
thanks

Simply chaining together what you have already provided:

def get_in_list(status)
‘x,j,m,jrn,fnk,foo,other’.split(’,’).include?(status)
end

Don’t know how pretty a hand-coded, comma-delimited string is, though.
=)

Cheers,
Bryan

Bryan Smith wrote:

Bryan

        return true

much better, thanks. the list is an example of a string in a database.
yeah, ugly.

thanks again
sk

You may want to consider a little refactoring when you are hard-coding
lists into methods. I also notice that you are returning true/false
based on a boolean operation. In those cases, returning the result of
the boolean operation yields the same value, and cuts out an ‘if’
statment and 4 lines of code:

STATUS_CODES = %w{x j m jrn fnk foo other}

def is_valid_code?(status_code)
STATUS_CODES.include?(status_code)
end

is_valid_code?(‘jrn’)

-Scott

nephish wrote:

       return false
    end

end

i dunno, just thought there might be a prettier way to do this.
any suggestions ?
thanks

Not prettier, but might be faster:

def get_in_list(status)
my_list = ‘x,j,m,jrn,fnk,foo,other’
/(?:^|,)#{Regexp.quote(status)}(?:,|$)/ === my_list
end

On 2006-11-11, nephish [email protected] wrote:

       return false
    end

end

i dunno, just thought there might be a prettier way to do this.
any suggestions ?
thanks

One possibility:

class HardCoded

List = 'x,j,m,jrn,fnk,foo,other'.split(',')

def self.contains(s)
	List.include?(s)
end

end

[test:]
#!/usr/bin/env ruby
$VERBOSE = true

require ‘hardcoded’

puts HardCoded.contains(‘bother’)
puts HardCoded.contains(‘other’)

:fr nephish [mailto:[email protected]]

def get_in_list(status)

my_list = ‘x,j,m,jrn,fnk,foo,other’

my_list_array = my_list.split(‘,’)

a candidate for chaining methods

if my_list_array.include?(status)

return true

else

return false

end

you are repeating and paraphrasing my_list_array.include?(status). lose
the returns, lose the ifs. this is ruby. r u a c programmer? :wink:

nonetheless, this is again a candidate for chaining.

end

i dunno, just thought there might be a prettier way to do this.

if you get a solution within a minute, including the typing, then that’s
pretty :slight_smile:

kind regards -botp

any suggestions ?

thanks

Peña wrote:

return false

if you get a solution within a minute, including the typing, then that’s pretty :slight_smile:

kind regards -botp

any suggestions ?

thanks

not a c programmer, just a newbie
appreciate everyones help, me stuff looks a lot better now.
-sk