SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Thread: .join(" ")?

  1. #1
    SitePoint Wizard lukeurtnowski's Avatar
    Join Date
    Mar 2003
    Location
    Coronado
    Posts
    1,665
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)

    .join(" ")?

    In the below program,
    Code:
    def translate(words)
      words.split(" ").map do |word|
        vowel = first_vowel(word)
        word = word.slice(vowel..-1) + word[0,vowel] + "ay"
      end.join(" ")
    
    end
    why is there a .join right after the first block?
    "Oh, and Jenkins--apparently your mother died this morning."

  2. #2
    padawan silver trophybronze trophy markbrown4's Avatar
    Join Date
    Jul 2006
    Location
    Victoria, Australia
    Posts
    4,117
    Mentioned
    28 Post(s)
    Tagged
    2 Thread(s)
    split() takes a string and returns an array
    map() takes an array, modifies each item and returns a new array
    join() turns the array back into a string putting a space between each item

    It is a little odd to see methods directly after a block but it can be done because the block returns a value that can have methods called on it.
    It's more common to see this done with simple blocks on one line.
    Code ruby:
    words.map{ |word| word + "ay" }.join(" ")

  3. #3
    SitePoint Wizard lukeurtnowski's Avatar
    Join Date
    Mar 2003
    Location
    Coronado
    Posts
    1,665
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    is that the best way
    "Oh, and Jenkins--apparently your mother died this morning."

  4. #4
    padawan silver trophybronze trophy markbrown4's Avatar
    Join Date
    Jul 2006
    Location
    Victoria, Australia
    Posts
    4,117
    Mentioned
    28 Post(s)
    Tagged
    2 Thread(s)
    When the blocks have more than one line of code it's standard to use do and end.
    Something like this may be more readable.
    Code ruby:
    def translate(words)
      words = words.split(" ").map do |word|
        vowel = first_vowel(word)
        word.slice(vowel..-1) + word[0,vowel] + "ay"
      end
     
      words.join(" ")
    end

  5. #5
    SitePoint Wizard lukeurtnowski's Avatar
    Join Date
    Mar 2003
    Location
    Coronado
    Posts
    1,665
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    thx
    "Oh, and Jenkins--apparently your mother died this morning."


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •