Ruby/Language Basics/Interpolating

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Add extra # sign to interpolation

number = 5
puts "We"re ##{number}!"                             # => "We"re #5!"



Call integer.to_s and Interpolation

x = 10
y = 20
puts x.to_s + " + " + y.to_s + " = " + (x + y).to_s
puts "#{x} + #{y} = #{x + y}"



Compare string after interpolation

number = 5
"#{number}" == "5"                             # => true



Constant Interpolation

puts "It"s a #{"bad " * 5}world"



Do a calculation in interpolation block

"I"ve set x to #{x = 5; x += 1}."       # => "I"ve set x to 6."
x                                       # => 6



Escape theinterpolation string

"\#{foo}"                               # => "\#{foo}"
"#{foo}"                                # => "\#{foo}"



Interpolating Variables in Double-Quoted Strings

temperature = 36
puts "The temperature is " + String(temperature) + "."
puts "The temperature is #{temperature}."



Interpolation

x = 10
y = 20
puts "#{x} + #{y} = #{x + y}"
10 + 20 = 30



Interpolation in Here document

name = "Mr. Lorum"
email = <<END
Dear #{name},
END



Number value Interpolation

 
temperature = 36
puts "The temperature is #{temperature}."
temperature = temperature + 5
puts "Now the temperature is #{temperature}."



Put class into interpolation block

%{Here is #{class InstantClass
   def bar
      "some text"
    end
  end
  InstantClass.new.bar
}.}



The #{ interpolates the result ofnto the string at that position

puts "100 * 5 = #{100 * 5}"



Use string method in interpolation

text = "this is a test"
puts "Split method: #{text.split.length}"



Using expression substitution

# you can grab an argument off the command line and add it to the output.
#!/usr/bin/env ruby
puts "Hello, #{ARGV[0]}!"



You can interpolate strings too

x = "cat"
puts "The #{x} in the hat"