Advertisement
Guest User

Untitled

a guest
Jun 3rd, 2015
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. What is the difference between:
  2.  
  3. "h" + "a" * 10
  4.  
  5. and
  6.  
  7. ("h" + "a") * 10
  8.  
  9. and why are they different?
  10.  
  11. "h" + "a" * 10 results in "haaaaaaaaaa"
  12. It concatonates the "h" and the "a" once, while adding the "a" ten times, as you've instructed.
  13. ("ha" + "a") * 10 results in "hahahahahahahahahaha"
  14. It concatonates the "h" and the "a" into a string ten times, since the parentheses indicate the * 10 should apply to everything within.
  15.  
  16. Interestingly, while experimenting with this, I learned that in order for multiplication to work on a string, you have to start your line of code with a string. If you start with a fixnum, it will result in an error. However, if you start with a string, you can add any amount of math behind it, and it will work. For example, 10 * 10 * ("I will not" + " swallow my Ruby.") results in an error, but ("I will not" + " swallow my Ruby.") * 10 * 10 correctly displays the entire string 100 times.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement