Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

syntax

ruby

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?

like image 933
slhck Avatar asked Nov 02 '11 12:11

slhck


2 Answers

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.

like image 105
Sergio Campamá Avatar answered Nov 02 '22 14:11

Sergio Campamá


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
like image 37
WarHog Avatar answered Nov 02 '22 13:11

WarHog