DISQUS

CSCI E-168, Fall 2007: Your one-liners?

  • steveharris · 2 years ago
    Proposed 1-liner:

    Hash#invert returns a new hash where the keys of the new hash are the values of the old hash, and vice-versa. If the original hash contains multiple keys that map to the same value, the new hash will contain a single entry for that value (now the new key) and which of the original keys becomes the new value is not predictable.

    Write a one-liner which inverts a hash, but where each value in the new hash is an array containing all the keys of the original hash.

    Now, write a one-liner like the above, but if there is only one (new) value, it should be a simple value, not an array.

    - Steve
  • Philipp · 2 years ago
    This is a little tricky, since punctuation gets in the way (you can't use a plain "split" because those "Indians" at the end have a trailing ".")
    I think this covers most situations, but "\b" may be a little obscure.

    s.split(/\b/).map {|w| d.include?(w) ? w[0].chr + "*" * (w.length - 1) : w}.join
  • Philipp · 2 years ago
    Plus, you can't censor things containing a mix of word and non-word characters. If you put "can't" in your banned word list, it won't be filtered out.
    I'll leave the substring-based solution to someone else.
    Also, what I posted censors case-sensitively. That probably ought to be corrected, too. Making it:
    d.map {|b| b.upcase}.include?(w.upcase)
    should take case of that.
    Oneliners that try to cover all the bases seem to get quite ornate.
  • jgn · 2 years ago
    Nice!
  • Mhoram · 2 years ago
    d.inject(a) { |censored, bad_word| censored.gsub( Regexp.new( bad_word ), '*' * bad_word.length) }
  • jgn · 2 years ago
    Can you add some code to show it working . . . ?
  • jgn · 2 years ago
    Good one.