1

Regarding the exercises in Michael Hartl's RoR Tutorial in lesson 4.3.3 (Hashes & Symbols):

"Define a hash with symbol keys corresponding to name, email, and a “password digest”, and values equal to your name, your email address, and a random string of 16 lower-case letters."

I am hoping to get some input and/or alternative & 'better' solutions to this (or at least some criticism regarding my solution).

def my_hash
  a = ('a'..'z').to_a.shuffle[0..15].join
  b = { name: "John", email: "[email protected]", password: a }
  return b
end

puts my_hash

(Yes I realize this is a very simple exercise and apologize if it has been asked before.)

1 Answer 1

3

There are many 2 improvements could be made:

  1. Use Array#sample to get random letters (it has an advantage: the letter might in fact repeat in the password, while shuffle[0..15] will return 16 distinct letters);
  2. Avoid redundant local variables and especially return.

Here you go:

def my_hash
  {
    name: "John",
    email: "[email protected]",
    password: ('a'..'z').to_a.sample(16).join
  }
end

puts my_hash

Bonus:

I accidentaly found the third glitch in the original code. It should probably be:

def my_hash
  {
    name: "Brandon",
    email: "[email protected]",
    password: ('a'..'z').to_a.sample(16).join
  }
end

:)

Sign up to request clarification or add additional context in comments.

6 Comments

That's cool. I havn't come across the Enumerable#sample yet but I can see the advantage there. Thanks! Also, wondering if it is just a matter of taste or best practice not to have all of the key/value pairs on a single line?
Regarding single line: here it’s mostly a matter of respecting those reading from smartphones and having not-so-wide screens. AFAIR, rubocop has a default rule to have lines not wider than 80 characters. But it’s definitely up to code owner/team to set up such rules.
ok..that's good to know. I have used rubocop but wasn't aware of that rule. Very helpful. lol... And you're right about that glitch.
There are also arguments that it makes changes easier to track, for example using a diff on a git change. It isolates the logical components so you see exactly what has changed more easily (e.g. if the code for the password changed).
@DavidAldridge well, all modern git diff pagers do support highlighting changes inside lines, but yes, I agree, tracking changes matters here.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.