Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rubocop Offense: Use the return of the conditional for variable assignment and comparison

Tags:

ruby

rubocop

My Rubocop offense is telling me I need to 'Use the return of the conditional for variable assignment and comparison'

While I tried fixing it, it gave me another offense that my 'method line is too long'.

I've tried refactoring to another method but my code broke.

How do I shorten or refactor this code ?

HSH = { 'a' => 'z', 'b' => 'y', 'c' => 'x', 'd' => 'w', 'e' => 'v', \
        'f' => 'u', 'g' => 't', 'h' => 's', \
        'i' => 'r', 'j' => 'q', 'k' => 'p', 'l' => 'o', 'm' => 'n' }.freeze


def encoder(str)
  encoded_string = ''
  str.chars.each do |char|
    encoded_string = if HSH.key?(char) then encoded_string += HSH[char]
                     elsif HSH.invert.key?(char) then encoded_string += HSH.invert[char]
                     else encoded_string += char
                     end
  end
  encoded_string
end

When I ran my test suite, everything was ok.

But the rubocop offense gave me method line is too long.

like image 460
cguy Avatar asked Nov 21 '25 14:11

cguy


2 Answers

No hash:

ALPHABET = ("a".."z").to_a.join

def encoder(str)
  str.tr(ALPHABET, ALPHABET.reverse)
end
like image 146
steenslag Avatar answered Nov 24 '25 04:11

steenslag


HSH = {
  'a' => 'z', 'b' => 'y', 'c' => 'x',
  'd' => 'w', 'e' => 'v', 'f' => 'u',
  'g' => 't', 'h' => 's', 'i' => 'r',
  'j' => 'q', 'k' => 'p', 'l' => 'o',
  'm' => 'n'
}.freeze

def encoder(str)
  str.chars.map { |char| HSH[char] || HSH.invert[char] || char }.join
end
like image 41
ndnenkov Avatar answered Nov 24 '25 06:11

ndnenkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!