Deleting first and last array element in one line? - ruby

How can I delete the first and last element in one line in a clever way?
I've tried:
names = %w[Go Go Go Power Rangers Go]
names.shift.pop
This fails because, I believe, both shift and pop return the value removed, which is then passed onto the following function, raising an error.
I also tried to make this work with delete_at, but it does not allow an array parameter and thus I get no further in my quest to make this a one-liner.
Any ideas?
Note: I value minimalism

_, *names, _ = %w[Go Go Go Power Rangers Go]
names #=> ["Go", "Go", "Power", "Rangers"]
Or if you already have the whole array as names, then:
names = %w[Go Go Go Power Rangers Go]
_, *names, _ = names
names #=> ["Go", "Go", "Power", "Rangers"]

You can use names = names[1..-2], but you shouldn't. Just use names.pop; names.shift and be done with it.

How about this?
names.slice!(1..-2)
Really though, as others have said, there's nothing wrong with:
names.pop
names.shift

I really like this solution:
_, *names, _ = names
It is very cool, is not it?
Also, I would use another variable (funcional style)
_, *new_names, _ = names
Edit: Sorry I realised that #sawa already post this solution.

Related

How to split a string but keep delimiters as separate elements

I have several strings that include various symbols like the following two examples:
z=y+x
#symbol
and I want to split the strings such that I have the resulting slices:
[z = y + x]
[# symbol]
A few things I've looked at and tried:
I've looked at this question but it seems as though golang doesn't support lookarounds.
I know this solution exists using strings.SplitAfter, but I'm looking to have the delimiters as separate elements.
I tried replacing the symbol (e.g. "+") with some variant (e.g. "~+~") and doing a split on the surrounding characters (e.g. "~"), but this solution is far from elegant and runs into problems if I need to do a conditional replacement depending on the symbol (which golang doesn't seem to support either).
Perhaps I've misunderstood some of the previous question and their respective solutions.
I used a modified version of Go's strings.Split implementation https://golang.org/src/strings/strings.go?s=7505:7539#L245
func Test(te *testing.T) {
t := tester.New(te)
t.Assert().Equal(splitCharsInclusive("z=y+x", "=+"), []string{"z", "=", "y", "+", "x"})
t.Assert().Equal(splitCharsInclusive("#symbol", "#"), []string{"", "#", "symbol"})
}
func splitCharsInclusive(s, chars string) (out []string) {
for {
m := strings.IndexAny(s, chars)
if m < 0 {
break
}
out = append(out, s[:m], s[m:m+1])
s = s[m+1:]
}
out = append(out, s)
return
}
This is limited to single characters to split on. And passing something like splitCharsInclusive("(z)(y)(x)", "()") might not get you the output you want, as you'd get a few empty strings in the response. But hopefully this is a good starting point for the modifications you need.
Also, Go's version that I've linked calculates the length of the output array in advance, this is a nice optimization that I've decided to omit, but would likely be good to add back.

ruby, assign the var that is not nill

I have in the html the location variable sometimes is used with a class called "result-hood" sometimes is used with another class called "nearby"
location = result.search('span.result-hood').text[2..-2]
location2 = result.search('span.nearby').text[2..-2]
so if one of the above classes is not used the result is nill, my question is how to get always the one that is not nill, I was thinking about the ternary operator "?" , but don't know how to use it.
Thanks,
You want the || ("or") operator:
location || location2
It returns the left side if that is not nil or false, and otherwise it returns the right side.
CSS supports logical or operations using a comma as the delimiter, so your selector can just be:
location = result.search('span.result-hood,span.nearby').text[2..-2]
XPath also supports logical or operator itself, the equivalent XPath would look like
location = result.search('//span[#class="result-hood"]|//span[#class="nearby"]').text[2..-2]
Ternary operator in ruby:
loc = location.nil? ? location2 : location
Hope this works.
Since you're looking for one or the other you can reduce this code to:
location = result.search('span.result-hood').text[2..-2]
|| result.search('span.nearby').text[2..-2]
Where that search operation could be fairly expensive, so why run it twice when you might need to run it only once. Now that you've minimized it like this you can take it a step further:
location = %w[ span.result-hood span.nearby ].map do |selector|
result.search(selector).text[2..-2]
end.compact.first
This looks a little complicated but what it does is convert each selector into the text extracted from result.search(...).text[2..-2] and then take the first non-nil value.
That technically computes all possible bits of text before extracting, so you can make it "lazy" and evaluate each one in sequence instead, stopping at the first match:
location = %w[ span.result-hood span.nearby ].lazy.map do |selector|
result.search(selector).text[2..-2]
end.select(&:itself).first
The nice thing about this approach is you can clean it up a little by declaring a constant in advance:
LOCATIONS = %w[ span.result-hood span.nearby ]
Then later you have more minimal code like this that will automatically accommodate any changes made to that array both in terms of precedence and addition of others:
location = LOCATIONS.lazy.map do |selector|
result.search(selector).text[2..-2]
end.select(&:itself).first

Is there a more readable way to write for k, v in pairs(my_table) do ... end in lua if I never use k?

Is there a more readable way in lua to write:
for k, v in pairs(my_table) do
myfunction( v )
end
I'm never using k, so I'd like to take it out of the loop control, so it's clear I'm just iterating over the values. Is there a function like pairs() that only gives me a list of the values?
There is no standard function that only iterates values, but you can write it yourself if you wish. Here is such an iterator :
function values(t)
local k, v
return function()
k, v = next(t, k)
return v
end
end
But normally people just use pairs and discard the first variable. It is customary in this case to name the unused variable _ (an underscore) to clearly indicate the intent.
I've seen people use the _ variable instead of k or i.
why would you use the pairs() function if you don't want the key/value pairs of the table you're enumerating then?
for example, this is even shorter to type:
local t = {"asdf", "sdfg", "dfgh"}
for i=1, #t do
print(t[i])
end
otherwise, i always just did this:
local t = {"asdf", "sdfg", "dfgh"}
for _,v in pairs(t) do
print(v)
end
edit: for your scenario, where you want to enumerate only values in a table with non-numeric keys, probably the clearest thing you could do would be to write your own table iterator function like this:
local t = {["asdf"] = 1, ["sdfg"] = 2, ["dfgh"] = 3}
function values(tbl)
local key = nil
return function()
key = next(tbl, key)
return tbl[key]
end
end
for value in values(t) do
print(value)
end
then, it is very explicit that you're only traversing the values of the table t. like pairs(), this is not guaranteed to traverse in order since it uses next().
It's your coding style, really. If you can read it and you're consistent with it then it shouldn't matter.
However, I tend to use:
for i,c in
"i" standing for "index" and "c" standing for "child", but "v" for "value" works as well. And even if you're not using the index variable, it's still good practice.
Another thing you might do is:
for n = 1, 10
when dealing with numbers. But once again, it's you're coding style and as long as it's consistent you should be good.
From Lua Style Guide:
The variable consisting of only an underscore "_" is commonly used as a placeholder when you want to ignore the variable:
for _,v in ipairs(t) do print(v) end
Note: This resembles the use of "_" in Haskell, Erlang, Ocaml, and Prolog languages, where "_" takes the special meaning of anonymous (ignored) variables in pattern matches. In Lua, "_" is only a convention with no inherent special meaning though. Semantic editors that normally flag unused variables may avoid doing so for variables named "_" (e.g. LuaInspect is such a case).
So I would expect underscore (_) name is more readable for unused variables.

Is it possible to rename and block built-in functions temporarily?

I wish to temporarily rename a built-in symbol and use it with different name while block the main name of this symbol. For example, I wish the following code to print only "2" but not "1" and "3":
Block[{print = Print, Print}, Print[1]; print[2]; Print[3];]
In really the above code prints nothing.
Is it possible to make print working inside such code while completely block symbol Print?
Solutions like
With[{Print = f, print = Print}, Print[1]; print[2]; Print[3];]
are not suitable since Print is not really blocked inside such code.
The question appeared while thinking on a way to disable tracing of Message internals.
This is not very clean, but I believe it is serviceable.
Internal`InheritedBlock[{Print},
Unprotect[Print];
Print[x__] := Null /; ! TrueQ[$prn];
print[x__] := Block[{$prn = True}, Print[x]];
Print[1]; print[2]; Print[3];
]
If it is not acceptable to have the function replaced with Null in the return, you may need to use something like:
func[x__] := Hold[func[x]] /; ! TrueQ[$prn];
Followed by a ReleaseHold after the Block.
Or:
func[x__] := zz[x] /; ! TrueQ[$prn];
and then follow the Block with: /. zz -> func

Return popupmenu selection in MATLAB using one line of code

I have a GUI which uses a selection from a popupmenu in another callback. Is there a way to return the selected value of the popupmenu in only one line without creating any temporary variables? I've tried several solutions, but I've only managed two lines with one temporary variable:
Three lines:
list=get(handles.popupmenu1,'String');
val=get(handles.popupmenu1,'Value');
str=list{val};
Two lines:
temp=get(handles.popupmenu1,{'String','Value'});
str=temp{1}{temp{2}};
Can anyone shave it down to one?
PS, It's a dynamic menu, so I can't just use get(handles.popupmenu1,'Value') and ignore the string component altogether.
Here's a one-liner:
str = getCurrentPopupString(handles.popupmenu1);
And here's the definition of getCurrentPopupString
function str = getCurrentPopupString(hh)
%# getCurrentPopupString returns the currently selected string in the popupmenu with handle hh
%# could test input here
if ~ishandle(hh) || strcmp(get(hh,'Type'),'popupmenu')
error('getCurrentPopupString needs a handle to a popupmenu as input')
end
%# get the string - do it the readable way
list = get(hh,'String');
val = get(hh,'Value');
if iscell(list)
str = list{val};
else
str = list(val,:);
end
I know that's not the answer you were looking for, but it does answer the question you asked :)
I know this is stupid, but I couldn't resist:
list=get(handles.popupmenu1,'String'); str=list{get(handles.popupmenu1,'Value')};
I know that's not what you meant, but like the other answers above, it does answer your question... :-)
To make it a one-liner, I would simply create my own function (i.e. getMenuSelection) like Jonas illustrates in his answer. If you really want a true one-liner, here's one using CELLFUN:
str = cellfun(#(a,b) a{b},{get(handles.popupmenu1,'String')},{get(handles.popupmenu1,'Value')});
Very ugly and hard to read. I'd definitely go with writing my own function.
EDIT: And here's a slightly shorter (yet still equally ugly) one-liner using FEVAL:
str = feval(#(x) x{1}{x{2}},get(handles.popupmenu1,{'String','Value'}));

Resources