#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    2
    Rep Power
    0

    Refactoring if and unless into one if


    what is the best way to make the if and the unless into one line of code if n is passed into a method? Thank you.

    unless n.is_a? Integer
    return "n must be an integer."
    end

    if n <= 0
    return "n must be greater than 0."
    end
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,911
    Rep Power
    1045
    Hi,

    returning the error message as a string makes no sense. I guess you want something like this:

    Code:
    raise ArgumentError, 'must be a positive Integer' unless
      n.kind_of? Integer and n > 0
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    2
    Rep Power
    0
    Originally Posted by Jacques1
    Hi,

    returning the error message as a string makes no sense. I guess you want something like this:

    Code:
    raise ArgumentError, 'must be a positive Integer' unless
      n.kind_of? Integer and n > 0
    Thank you.
    Sorry. I realized I was trying to create two one oneliners instead of just one. So the following is what I meant and works.

    return "n must be an integer." unless n.is_a? Integer

    return "n must be greater than 0." if n <= 0

IMN logo majestic logo threadwatch logo seochat tools logo