slhck
slhck

Reputation: 38652

What is the meaning of the percent sign + pipe operator in Ruby, as in "%|"?

I'm trying to understand the script presented on this site:

#!/usr/bin/env ruby

require ENV['TM_SUPPORT_PATH'] + '/lib/escape.rb'

def terminal_script_filepath
  %|tell application "Terminal"
      activate
      do script "jsc -i #{e_as(e_sh(ENV['TM_FILEPATH']))}"
    end tell|
end

open("|osascript", "w") { |io| io << terminal_script_filepath }

Most importantly, the part where the function terminal_script_filepath begins with:

%| …
… |

… and where it is "parsed" in:

{ |io| io << terminal_script_filepath }

Which concepts of Ruby are used here?

I know that open() with a pipe helps me feed input to the STDIN of a process, but how does the input get from terminal_script_filepath to io? I also know the basic % operations with strings, like %w, but what does the pipe do here?

Upvotes: 10

Views: 3917

Answers (2)

WarHog
WarHog

Reputation: 8710

This is another example of string literal:

var = %|foobar|
var.class # => String

You can use any single non-alpha-numeric character as the delimiter, like so:

var = %^foobar^
var.class # => String

Upvotes: 4

Sergio Campam&#225;
Sergio Campam&#225;

Reputation: 746

It is a string. In ruby, you can define strings in may ways. Single or double quotes are the most common, %s is another. You can also define strings with any delimiter, as used in this script. For example %^Is also a string^, or %$Also a string$. You just have to make sure to not use those characters inside the string.

The << in this case is being used as a concatenation operation, appending the string to a file, or in this case, a pipe that listens to AppleScript.

Upvotes: 12

Related Questions