Skip to content

Commit

Permalink
Merge pull request #649 from nihathrael/lines
Browse files Browse the repository at this point in the history
Add @lines() method (#441)
  • Loading branch information
mmstick committed Dec 14, 2017
2 parents 037bfdb + dc271d5 commit bf1ef66
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions examples/array_methods.ion
Expand Up @@ -3,3 +3,4 @@ echo @split_at("onetwoone", "3")
echo @graphemes("onetwo", "3")
echo @bytes("onetwo")
echo @chars("onetwo")
echo @lines($unescape("firstline\nsecondline"))
1 change: 1 addition & 0 deletions examples/array_methods.out
Expand Up @@ -3,3 +3,4 @@ one twoone
o n e t w o
111 110 101 116 119 111
o n e t w o
firstline secondline
21 changes: 21 additions & 0 deletions manual/src/ch05-05-method.md
Expand Up @@ -455,12 +455,33 @@ echo $unescape($line)

The following are the currently-supported array methods.

- [lines](#lines)
- [split](#split)
- [split_at](#split_at)
- [bytes](#bytes)
- [chars](#chars)
- [graphemes](#graphemes)

### lines

Defaults to string variables. The supplied string will be split into one string per line in the input argument.

#### Examples

```ion
for line in @lines($unescape("first\nsecond\nthird")
echo $line
end
```

#### Output

```
first
second
third
```

### split

Defaults to string variables. The supplied string will be split according to a pattern specified
Expand Down
21 changes: 21 additions & 0 deletions src/parser/shell_expand/words/methods/arrays.rs
Expand Up @@ -34,6 +34,7 @@ impl<'a> ArrayMethod<'a> {
"graphemes" => self.graphemes(expand_func),
"bytes" => self.bytes(expand_func),
"chars" => self.chars(expand_func),
"lines" => self.lines(expand_func),
_ => Err("invalid array method"),
};

Expand Down Expand Up @@ -174,6 +175,11 @@ impl<'a> ArrayMethod<'a> {
.map(|c| c.to_string())
.select(self.selection.clone(), len))
}

fn lines<E: Expander>(&self, expand_func: &E) -> Result<Array, &'static str> {
let variable = self.resolve_var(expand_func);
Ok(variable.lines().into_iter().map(|line| line.to_string()).collect())
}
}

#[cfg(test)]
Expand All @@ -190,6 +196,7 @@ mod test {
match variable {
"FOO" => Some("FOOBAR".to_owned()),
"SPACEDFOO" => Some("FOO BAR".to_owned()),
"MULTILINE" => Some("FOO\nBAR".to_owned()),
_ => None,
}
}
Expand Down Expand Up @@ -413,4 +420,18 @@ mod test {
array!["F", "O", "O", "B", "A", "R"]
);
}

#[test]
fn test_lines() {
let method = ArrayMethod {
method: "lines",
variable: "$MULTILINE",
pattern: Pattern::StringPattern("3"),
selection: Select::All,
};
assert_eq!(
method.handle_as_array(&VariableExpander),
array!["FOO", "BAR"]
);
}
}

0 comments on commit bf1ef66

Please sign in to comment.