Equivalent in ruby of PHP's .= operator?
I'm looking to concatenate a string in a loop, like this, but in Ruby:
$fizz = file_get_contents($_SERVER['argv'][1]);
$output = "";
for($i=1;$i<=$fizz;$i++) {
if($i % 3 == 0 && !($i % 5 ==0)) {
$output .= "fizz\n";
}
else if($i % 5 == 0 && !($i % 3 ==开发者_开发问答0)) {
$output .= "buzz\n";
}
else if($i % 3 == 0 && $i % 5 == 0) {
$output .= "FizzBuzz\n";
}
}
print $output;
?>
I'm also interested in finding out what the name of the ".=" type operator is called so I can Google search these things better.
Using Ruby 1.8.6.
You are looking for Ruby's String#<<
.
So, your code might look like this:
variable << "fizz\n"
Here is the documentation for the << (aka concat) method.
I don't know Ruby, but a quick search for Ruby String Concatenation
(the operator is not a really an operator (PHP is just.. special, and not necessarily the good kind), it's called string concatenation) gives the following:
myString = "Welcome " + "to " + "Ruby!"
- Standard concatenation across most languages.
myString = "Welcome " "to " "Ruby!"
- Omits + sign
myString = "Welcome " << "to " << "Ruby!"
- c++ cout
style.
The content of myString
will all be "Welcome to Ruby"
.
Maybe you could even do +=
(equivilant to .=
)
Watch out for freeze strings.. apparently.
More info: http://www.techotopia.com/index.php/Ruby_String_Concatenation_and_Comparison
Is there a real reason you need to solve it this way? This can be expressed in Ruby like so:
(1..100).each do |number|
if number % 15 == 0
puts "#{number} FizzBuzz"
elsif number % 5 == 0
puts "#{number} Buzz"
elsif number % 3 == 0
puts "#{number} Fizz"
end
end
Using (1..100) is a range which mixes in Enumerable
so we can iterate over the items.
If the fizzbuzz problem allows for printing all numbers (as some interpretations do), then here's a variant of Caley Woods example above, showcasing the way case statements return values
(1..100).each do |number|
puts number.to_s << case 0
when number % 15
" FizzBuzz"
when number % 5
" Buzz"
when number % 3
" Fizz"
else
""
end
end
精彩评论